/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package salidasautomaticas.schedule;

import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import org.quartz.CronTrigger;
import org.quartz.Job;
import static org.quartz.JobBuilder.newJob;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.impl.StdSchedulerFactory;
import salidasautomaticas.main.Main;
import salidasautomaticas.services.SalidasServices;

/**
 *
 * @author sistem19user
 */
public class ProgramarSalidasJob implements Job{

    @Override
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        SalidasServices services = new SalidasServices();
        try {
            JSONArray listaHorarios = services.obtenerHorariosSalida();
            
            Iterator it = listaHorarios.iterator();
            int i =0;
            while(it.hasNext()){
                JSONObject objJSON = (JSONObject) it.next();
                String horaSalida = objJSON.getString("salida");
                System.out.println(horaSalida);
                programar(horaSalida, Integer.toString(i));
                i++;
            }
            
            
            
        } catch (Exception ex) {
            Logger.getLogger(ProgramarSalidasJob.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    private void programar(String horaSalida, String jobName){
        SchedulerFactory sf = Planificador.getInstance().getSchedulerFactory();
        Scheduler scheduler;
        
        String[] splitHora = horaSalida.split(":");
        
        try {
            scheduler = sf.getScheduler();
            JobDetail job = newJob(GenerarSalidasJob.class).withIdentity(jobName, "groupSalida1").build();

            String cronExpression = "0 %s %s * * ?";
            cronExpression = String.format(cronExpression, splitHora[1], splitHora[0]);
            
            CronTrigger trigger = newTrigger().withIdentity("triggerSalida"+jobName, "groupSalida1").withSchedule(cronSchedule(cronExpression))
                    .build();

            scheduler.scheduleJob(job, trigger);

            scheduler.start();
        } catch (SchedulerException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
