package com.atolcd.parapheur.repo.content.cleanup;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.transaction.UserTransaction;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.search.impl.lucene.QueryParser;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.CachingDateFormat;
import org.alfresco.web.bean.repository.Repository;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ParapheurCleaner
{
   private static Log logger = LogFactory.getLog(ParapheurCleaner.class);
   
   private NodeArchiveService nodeArchiveService;
   private SearchService searchService;
   private TransactionService transactionService;
   private Properties configuration;
   private int protectedDays = 7;

   /**
    * @param nodeArchiveService The nodeArchiveService to set.
    */
   public void setNodeArchiveService(NodeArchiveService nodeArchiveService)
   {
      this.nodeArchiveService = nodeArchiveService;
   }
   
   /**
    * @param searchService The searchService to set.
    */
   public void setSearchService(SearchService searchService)
   {
      this.searchService = searchService;
   }
   
   /**
    * @param transactionService the transactionService to set
    */
   public void setTransactionService(TransactionService transactionService)
   {
      this.transactionService = transactionService;
   }

   public Properties getConfiguration()
   {
       return configuration;
   }

   public void setConfiguration(Properties configuration)
   {
      this.configuration = configuration;
   }

   /**
    * @param protectedDays The protectedDays to set.
    */
   public void setProtectedDays(int protectedDays)
   {
      this.protectedDays = protectedDays;
      if (logger.isDebugEnabled())
      {
         if (this.protectedDays > 0)
            logger.debug("Protection des elements avant la purge fixee a : " + protectedDays + " jours");
         else
            logger.debug("Purge automatique desactivee");
      }
   }

   public void execute()
   {
      if (this.protectedDays > 0)
      {
         Date fromDate = new Date(0);
         Date toDate = new Date(new Date().getTime() - (1000L*60L*60L*24L*new Long(this.protectedDays)));
         
         if (toDate == null)
         {
            throw new RuntimeException("Erreur lors de la recuperation de la date limite");
         }
         
         SimpleDateFormat df = CachingDateFormat.getDateFormat();
         String strFromDate = QueryParser.escape(df.format(fromDate));
         String strToDate = QueryParser.escape(df.format(toDate));
         StringBuilder buf = new StringBuilder(128);
         buf.append("@").append(Repository.escapeQName(ContentModel.PROP_ARCHIVED_DATE))
            .append(":").append("[").append(strFromDate)
            .append(" TO ").append(strToDate).append("] ");
         
         String query = buf.toString();
         
         SearchParameters sp = new SearchParameters();
         sp.setLanguage(SearchService.LANGUAGE_LUCENE);
         sp.setQuery(query);

         //NodeRef archiveRootRef = this.nodeArchiveService.getStoreArchiveNode(Repository.getStoreRef());
         NodeRef archiveRootRef = this.nodeArchiveService.getStoreArchiveNode(
        	 new StoreRef(this.configuration.getProperty("spaces.store")));
         sp.addStore(archiveRootRef.getStoreRef());
         if (logger.isDebugEnabled())
         {
            logger.debug("Purge declenchee a partir de la requete suivante:");
            logger.debug(query);
         }
         
         UserTransaction tx = null;
         ResultSet results = null;
         try
         {
            tx = this.transactionService.getNonPropagatingUserTransaction(false);
            tx.begin();
            
            results = this.searchService.query(sp);
            this.nodeArchiveService.purgeArchivedNodes(results.getNodeRefs());
            
            tx.commit();
         }
         catch (Throwable err)
         {
            if (logger.isWarnEnabled())
               logger.warn("Erreur lors de la purge des elements : " + err.getMessage());
            try 
            { 
               if (tx != null) 
               {
                  tx.rollback();
               } 
            } 
            catch (Exception tex) 
            {
               ;
            }
         }
         finally
         {
            if (results != null)
            {
               results.close();
            }
         }
      }
   }
}
