/*
 * 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 java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import salidasautomaticas.util.Metodos;

/**
 *
 * @author sistem19user
 */
public class ProgramarSalidasTask extends TimerTask {

    @Override
    public void run() {

        try {
//            JSONArray listaHorarios = service.obtenerHorariosSalida();
            JSONArray listaHorarios = new JSONArray();
            String[] arraySalidas = {"10:29", "14:46", "14:50", "17:00", "17:30", "18:00"};

            for (String salida : arraySalidas) {
                listaHorarios.put(new JSONObject().put("salida", salida));
            }

            System.out.println("Listando horarios " + listaHorarios + "\n");

            Timer timer;
            TimerTask task;
            for(Iterator it = listaHorarios.iterator(); it.hasNext();) {
                JSONObject obj = (JSONObject) it.next();
                String horaSalida = obj.getString("salida");

                System.out.println("Leyendo hora de salida " + horaSalida);
                if (validarProgramacionSalida(horaSalida)) {
                    System.out.println("Programando hora de salida " + horaSalida);
                    Date horaEjecucion = Metodos.getHoraEjecucion(horaSalida);

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

                    System.out.println("Timer " + timer);
                } else {
                    System.out.println("Ya pasó la hora");
                }
                System.out.println();
            }

        } catch (Exception ex) {
            Logger.getLogger(ProgramarSalidasTask.class.getName()).log(Level.SEVERE, null, 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;
    }
}
