package com.k_int.aggregator.dpp.timers;

import com.k_int.aggregator.dpp.timers.datamodel.CollectionUpdateTimerHDO;
import com.k_int.aggregator.dpp.timers.datamodel.UpdateTimerStatusEnum;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.context.ApplicationContext;

/**
 * Task due class to handle the case where it is time that a collection auto
 * update should run
 */
public class CollectionAutoUpdateTask extends TimerTask {

    private ExecutorService thread_pool;
    private ApplicationContext ctx;
    private static Logger log = Logger.getLogger(CollectionAutoUpdateTask.class);

    public CollectionAutoUpdateTask(ExecutorService thread_pool, ApplicationContext ctx) {
        this.thread_pool = thread_pool;
        this.ctx = ctx;
    }

    @Override
    public void run() {
        log.debug("Running collection auto update due task " + new Date());
        Session session = null;
        SessionFactory sf = (SessionFactory) ctx.getBean("AggregatorSessionFactory");

        try {
            session = sf.openSession();
            //GregorianCalendar calendar = new GregorianCalendar();   
            //need sort out the matching of dates
            Query q = session.createQuery("Select x from com.k_int.aggregator.dpp.timers.datamodel.CollectionUpdateTimerHDO x where x.nextDueTime < CURRENT_TIMESTAMP() AND x.timerStatus = ?");
            q.setParameter(0,UpdateTimerStatusEnum.IDLE);
            CollectionUpdateTimerHDO timer = (CollectionUpdateTimerHDO)q.uniqueResult();
            
            if ( timer != null ) {
                // The timer is due - handle that.
                
                // Set up the job and then submit it..
                CollectionAutoUpdateJob job = new CollectionAutoUpdateJob(ctx);
                
                thread_pool.submit(job);
            } else {
                // No timer due - don't need to do anything
                log.debug("The collection auto update timer is not due to run yet");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (session != null && session.isOpen() ) {
                    session.close();
                }
            } catch (Exception ex) {
            }
        }

    }
}
