package com.fp.general.scheduler;

import java.util.List;

import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.fp.general.exception.GeneralException;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.data.ThreadFacade;
import com.fp.persistence.pgeneral.schedule.TgeneScheduleEvent;
import com.fp.persistence.pgeneral.schedule.TgeneScheduleParameters;

/**
 * Clase que se encarga de ejecutar tareas calendarizadas, que se parametrizan en TgeneSchdeleEven.
 * @author Jorge Vaca
 * @version 2.1
 */
public class MiaScheduler {

	private MiaScheduler cahce; 
	private Scheduler scheduler;
	
	public void init()  {
		try {
			SchedulerFactory sfact = new StdSchedulerFactory();
			scheduler = sfact.getScheduler();
			scheduler.start();
			//Obtine lista de eventos a procesar.
			List<TgeneScheduleEvent> ldata = TgeneScheduleEvent.find(PersistenceHelper.getEntityManager());
			if(ldata == null || ldata.isEmpty()){
				return;
			}			
			TgeneScheduleParameters params = TgeneScheduleParameters.find(PersistenceHelper.getEntityManager(), 
					ThreadFacade.getSessionData().getCompany());
			if(params == null){
				throw new GeneralException("GENE-0034", "PARAMETROS PARA EJECUTAR TAREAS CALENDARIZADAS NO DEFINIDOS EN TGENSCHEDULEPARAMETERS", ThreadFacade.getSessionData().getCompany());
			}
			//Calendariza tareas por evento.
			for (TgeneScheduleEvent obj : ldata) {
				//Va dentro del for para crear un nuevo JobDataMap de parametros por cada ejecucion.
				JobDataMap jdm = this.fillMap(params);			
				this.processByEvent(obj,jdm);
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	/**
	 * Metodo que define tareas calendarizadas, de acuerdo a la definicion del evento. 
	 * @param event  Objeto que contien caracteristicas de ejecucion de un evento.
	 * @param jdm  Map con parametros que se asocian a la tarea calendarizada.
	 * @throws Exception
	 */
	private void processByEvent(TgeneScheduleEvent event,JobDataMap jdm) throws Exception {
		jdm.put("evento", event.getPk());
		//crea un jobdetail
		JobDetail jd = new JobDetail(event.getPk(),event.getPk(), SchedulerJob.class);
		jd.setJobDataMap(jdm);
		//crea el cron segundos minutos horas diames mes diasemana
		//CronTrigger ct = new CronTrigger(event.getPk(),event.getPk(),  "0 05 15 ? * 2-6");
		String cron =  ""+event.getExesecond()+" "+event.getExeminute()+" "+event.getExehour()+" ? * "+event.getBeginweekday()+"-"+event.getEndweekday();
		CronTrigger ct = new CronTrigger(event.getPk(),event.getPk(), cron);
		scheduler.scheduleJob(jd, ct);
	}
	
	/**
	 * Crea un map con los datos de parametros de ejecucion de una tarea automatica.
	 * @param params  Parametros de ejecucion de tareas automaticas.
	 * @return  JobDataMap
	 * @throws Exception
	 */
	private JobDataMap  fillMap(TgeneScheduleParameters params) throws Exception {
		JobDataMap jdm = new JobDataMap();
		jdm.put("cia", params.getPk());
		jdm.put("suc", params.getBranchcode());
		jdm.put("ofi", params.getOfficecode());
		jdm.put("area", params.getAreacode());
		jdm.put("ter", params.getTerminalcode());
		jdm.put("can", params.getChannelcode());
		jdm.put("usu", params.getUsercode());
		return jdm;
	}
	
    public void detenerJob() throws Exception{
        scheduler.shutdown();
    }
	
}
