package eu.dnetlib.espas.data.harvest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

public class CSWHarvester
{
   {  // Class wide initialization.
      logger = Logger.getLogger(CSWHarvester.class);
   }
   public static final int POOL_AWAIT_TERMINATION_INTERVAL = 60;
   protected static Logger logger = null;
   protected ExecutorService executorService = null;

   public CSWHarvester()
   {
      this.initialize();
   }

   public void initialize()
   {
      this.executorService = Executors.newCachedThreadPool();
   }

   public void shutdown()
   {
      this.executorService.shutdown();
   }

   public void shutdownAndWaitTermination()
   {
      // Disable new tasks from being submitted.
      this.executorService.shutdown();
      try
      {
         // Wait for existing tasks to terminate
         if(!this.executorService.awaitTermination(CSWHarvester.POOL_AWAIT_TERMINATION_INTERVAL, TimeUnit.SECONDS))
         {  // Cancel currently executing tasks
            this.executorService.shutdownNow();
            if(!this.executorService.awaitTermination(CSWHarvester.POOL_AWAIT_TERMINATION_INTERVAL, TimeUnit.SECONDS))
            {  // Failed to cancel currently executing tasks.
               logger.error("Thread pool did not terminate!");
            }
         }
      }
      catch(InterruptedException e)
      {
         logger.error("Failed to shutdown the harvester's thead pool.", e);
         this.executorService.shutdownNow();
         Thread.currentThread().interrupt();
      }
   }

   public void execute(RecordsHarvester recordsHarvester)
   {
      executorService.execute(recordsHarvester);
   }

   public ExecutorService getExecutorService()
   {
      return executorService;
   }

   public void setExecutorService(ExecutorService executorService)
   {
      this.executorService = executorService;
   }
}
