/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rjconsultores.ventaboletos.web.utilerias;

import com.rjconsultores.ventaboletos.entidad.Constante;
import com.rjconsultores.ventaboletos.service.ConstanteService;
import com.rjconsultores.ventaboletos.web.gui.controladores.job.GeneracionCorridaJob;
import com.rjconsultores.ventaboletos.web.utilerias.spring.AppContext;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.WebApp;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;

/**
 *
 * @author gleimar
 */
public class MyAppInit implements org.zkoss.zk.ui.util.WebAppInit {

    private static Logger log = Logger.getLogger(MyAppInit.class);
    SchedulerFactory schedFact = new StdSchedulerFactory();
    Scheduler sched;

    public Scheduler getSched() {
        return sched;
    }

    public void setSched(Scheduler sched) {
        this.sched = sched;
    }

    public SchedulerFactory getSchedFact() {
        return schedFact;
    }

    public void setSchedFact(SchedulerFactory schedFact) {
        this.schedFact = schedFact;
    }

    @Override
    public void init(WebApp wapp) throws Exception {
        Labels.register(new MyLabelLocatorGeneral((ServletContext) wapp.getNativeContext()));
        Labels.register(new MyLabelLocatorCliente((ServletContext) wapp.getNativeContext()));

        //Generacion Automatica de Corridas
        jobGeneracionCorridas();
    }

    private Integer[] horaExecucion() {

        ApplicationContext appContext = AppContext.getApplicationContext();

        BeanFactory factory = (BeanFactory) appContext;
        ConstanteService cs = (ConstanteService) factory.getBean("constanteService");

        Constante constante = cs.buscarPorNomeConstante("HORA_GENERACION_CORRIDA");

        Integer[] arrayHoraMinuto = new Integer[2];
        arrayHoraMinuto[0] = 1;
        arrayHoraMinuto[1] = 0;

        if ( (constante == null) || (constante.getValorconstante() == null)) {
            return null;
        }

        int hora = 1;
        int minuto = 0;
        try {
            String[] vlrContante = constante.getValorconstante().split(":");

            hora = Integer.parseInt(vlrContante[0]);
            minuto = Integer.parseInt(vlrContante[1]);
            if (hora < 0 || hora > 23) {
                hora = 1;
            }
            if (minuto < 0 || minuto > 59) {
                minuto = 0;
            }

            arrayHoraMinuto[0] = hora;
            arrayHoraMinuto[1] = minuto;

        } catch (Exception e) {
            log.error("Param hora geracion corrida invalido : " + constante.getValorconstante());
            arrayHoraMinuto[0] = 1;
            arrayHoraMinuto[1] = 0;
        }

        return arrayHoraMinuto;

    }

    private void jobGeneracionCorridas() {
        try {
            sched = schedFact.getScheduler();

            JobDetail jobDetail = new JobDetail("GeneracionCorridas", null, GeneracionCorridaJob.class);

            Integer[] hora = horaExecucion();
            
            if(hora == null){
            	log.debug("constante HORA_GENERACION_CORRIDA não habilitada.");
            	return;
            }

            log.debug("Horario de geracao de corrida : " + hora[0] + ":" + hora[1]);

            Trigger trigger = TriggerUtils.makeDailyTrigger("generacionCorridasTrigger", hora[0], hora[1]);

            //TESTE TRIGGER
            //Trigger trigger = TriggerUtils.makeImmediateTrigger("generacionCorridasTrigger", 1, 1000);

            trigger.setName("generacionCorridasTrigger");
            
            JobDetail job = sched.getJobDetail(jobDetail.getName(), jobDetail.getGroup());

			log.info("Job="+jobDetail.getName() +"." +jobDetail.getGroup());
			
			if (job != null) {
				log.info("Job ya existia");
				boolean deleted= sched.deleteJob(job.getName(), Scheduler.DEFAULT_GROUP);
				log.info("Deleted="+deleted);
			}
            
            sched.scheduleJob(jobDetail, trigger);

            sched.start();

        } catch (SchedulerException ex) {
            log.error(ex);
        }
    }
}
