/*
 * 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.time.LocalTime;
import java.util.Date;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import salidasautomaticas.services.SalidasServices;
import salidasautomaticas.util.Metodos;

/**
 *
 * @author sistem19user
 */
public class ProgramarSalidasTask extends TimerTask {
    private static final Logger log = LogManager.getLogger(ProgramarSalidasTask.class);
    private static SalidasServices service = new SalidasServices();
    
    @Override
    public void run() {

        try {
//            JSONArray listaHorarios = service.obtenerHorariosSalida();
            JSONArray listaHorarios = new JSONArray();
            String[] arraySalidas = {"15:26", "14:46", "14:50", "17:00", "17:30", "18:00"};
            for (String salida : arraySalidas) {
                listaHorarios.put(new JSONObject().put("salida", salida));
            }
                             
            Timer timer;
            TimerTask task;
            
            log.info("horario leido= "+listaHorarios);
            for(Iterator it = listaHorarios.iterator(); it.hasNext();) {
                JSONObject obj = (JSONObject) it.next();
                String horaSalida = obj.getString("salida");

                log.trace("Leyendo hora de salida " + horaSalida);
                if (validarProgramacionSalida(horaSalida)) {
                    log.info("Programando hora de salida " + horaSalida);
                    Date horaEjecucion = Metodos.getHoraEjecucion(horaSalida);

                    timer = new Timer();
                    task = new ActualizarSalidaTask(timer, horaSalida);
                    timer.schedule(task, horaEjecucion);

                    log.trace("Timer " + timer);
                } else {
                    log.trace("Ya pasó la hora");
                }
            }

        } catch (Exception ex) {
            log.error("error", ex);
        }

    }

    private boolean validarProgramacionSalida(String horaSalida) {
        boolean valido = false;
        String[] splitHora = horaSalida.split(":");
        int min = Integer.parseInt(splitHora[1]);
        int hora = Integer.parseInt(splitHora[0]);
        int cantMinutos = hora * 60 + min;

        LocalTime timeSystem = LocalTime.now();

        int cantMinutosSistema = timeSystem.getHour() * 60 + timeSystem.getMinute();

        if (cantMinutos > cantMinutosSistema) {
            valido = true;
        }

        return valido;
    }
}
