/*
 * 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.mysqldao;

import java.sql.Connection;
import java.time.LocalDate;
import org.json.JSONArray;
import org.json.JSONObject;
import salidasautomaticas.dao.SalidasDAO;
import salidasautomaticas.util.EstandarDAO;

/**
 *
 * @author sistem19user
 */
public class SalidasMysqlDAO implements SalidasDAO {

    @Override
    public JSONArray obtenerHorariosSalida() throws Exception {
        Connection cn = MysqlDAOFactory.getConneccion("nuevo");
        int diaSemana = obtenerDiaSemana();
        String query = "select ? as salida from personal inner join "
                + "cargo on (personal.codcargo=cargo.codcargo) where NULLIF(? , '') is NOT null and retirado=0 GROUP BY ?";

        if (diaSemana >= 1 && diaSemana <= 5) {
            query = query.replaceAll("\\?", "salidaLV");
        } else if (diaSemana == 6) {
            query = query.replaceAll("\\?", "salidaS");
        }
        
        
        JSONArray jsonArray = EstandarDAO.getInstance().consultar(cn, query);

        return jsonArray;
    }

    private int obtenerDiaSemana() {
        int diaSemana;
        LocalDate date = LocalDate.now();
        diaSemana = date.getDayOfWeek().getValue();

        return diaSemana;
    }

    @Override
    public JSONObject actualizarSalida() throws Exception {
        JSONObject resultado = null;
        Connection cn = MysqlDAOFactory.getConneccion("nuevo");
        String queryPersonal = "select codper from personal where salidaLV='10:00' and retirado=0";
        JSONArray jsonArray = EstandarDAO.getInstance().consultar(cn, queryPersonal);
        
        for(int i=0; i<jsonArray.length(); i++){
            JSONObject objJSON = (JSONObject) jsonArray.get(i);
            String codper = objJSON.getString("codper");
            String query = "update asistencia set horasal=2, minsal=0 where codper=?";
            JSONArray parametros = new JSONArray();
            parametros.put(codper);
            resultado = EstandarDAO.getInstance().ejecutar(cn, query);  
        }
        
        
        
        
        return resultado;
    }
}