/*
 * 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 com.arrebol.taxiservicios.controller.sp.report;

import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.sp.report.ReportReleaseResource;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Oscar
 */
public class ReleaseController extends ConnectionManager implements Serializable {
    
    /**
     *
     * @param starDate
     * @param endDate
     * @return
     */
    public List<ReportReleaseResource> fillDatatable(String starDate, String endDate, String idLocation) {
        logger.info("Searching all ReleaseResource..");

        List<ReportReleaseResource> list = new ArrayList<>();
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            List<Object> rows = session.createNativeQuery(query)
                    .setParameter("starDate", starDate)
                    .setParameter("endDate", endDate)
                    .setParameter("location", idLocation)
                    .getResultList();

            transaction.commit();

            rows.forEach((row) -> {
                try {
                    Object[] results = (Object[]) row;
                    SimpleDateFormat fechaInicial = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat fechaFinal = new SimpleDateFormat("yyyy-MM-dd");
                    
                    ReportReleaseResource pay = new ReportReleaseResource(
                            null == results[0] ? null : results[0].toString(),
                            null == results[1] ? null : results[1].toString(),
                            null == results[2] ? null : results[2].toString(),
                            null == results[3] ? null : fechaInicial.parse(results[3].toString()),
                            null == results[4] ? null : fechaFinal.parse(results[4].toString()),
                            Integer.valueOf(null == results[5] ? "0" : results[5].toString()),
                            null == results[6] ? null : results[6].toString(),
                            null == results[7] ? null : results[7].toString(),
                    Integer.valueOf(null == results[8] ? "0" : results[8].toString()));
                    
                    list.add(pay);
                } catch (ParseException ex) {
                    java.util.logging.Logger.getLogger(ReleaseController.class.getName()).log(Level.SEVERE, null, ex);
                }
            });

            logger.info("Success fillDatatable");
        } catch (HibernateException e) {
            logger.error("Report release resource", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillDatatable(" + starDate + " " + endDate + ") ", e);
            rollback(transaction);
        }
        return list;
    
    }
    
    private static final long serialVersionUID = -1L;

    final Logger logger = LogManager.getLogger(getClass());
    
    private String query = "SELECT \n" +
"r.id,\n" +
"' ' as chofer,\n" +
"if(ISNULL(t.id) , \"\", CONCAT(t.economic_number, ' - ', v.name)) as taxi,\n" +
"DATE(r.start_date) as fecha_inicial,\n" +
"DATE(r.end_date) as fecha_final,\n" +
"totalDaysInARangeOfDates(r.start_date, IF(ISNULL(r.end_date), CURDATE(), r.end_date), TRUE) as num_days,\n" +
"IF(ISNULL( \n" +
"(select GROUP_CONCAT(concat(' ',srvc.name)) from CONTRACT cntrct inner join CONTRACT_HAS_SERVICE chs on cntrct.id = chs.contract_id inner join SERVICE srvc on chs.service_id = srvc.id where cntrct.taxi_id = t.id and cntrct.active = 1) \n" +
") ,'', \n" +
"(select GROUP_CONCAT(concat(' ',srvc.name)) from CONTRACT cntrct inner join CONTRACT_HAS_SERVICE chs on cntrct.id = chs.contract_id inner join SERVICE srvc on chs.service_id = srvc.id where cntrct.taxi_id = t.id and cntrct.active = 1) \n" +
") AS contract_service, \n" +
"IF(ISNULL(c.ID) , \"\", CONCAT(c.first_name, ' ', c.last_name)) as cliente, \n" +
"totalDaysInARangeOfDates(STR_TO_DATE(:starDate, '%Y-%m-%d'), STR_TO_DATE(:endDate,'%Y-%m-%d'), TRUE) as num_days_dates \n" +
"FROM RELEASE_RESOURCE r \n" +
"INNER JOIN TAXI t ON t.id = r.taxi_id \n" + 
"INNER JOIN VEHICLE v ON t.vehicle_id = v.id \n" + 
"INNER JOIN PERSON c ON t.customer_id = c.id \n" + 
"WHERE t.active = 1 AND DATE(r.start_date) BETWEEN STR_TO_DATE(:starDate, '%Y-%m-%d') AND STR_TO_DATE(:endDate,'%Y-%m-%d') and t.id_location = :location AND (SELECT COUNT(so.id) FROM SERVICE_ORDER so WHERE so.service_order_type IN ('PENDING','APPROVED','PROGRESS',"+
"'PASE_TALLER') AND so.taxi_id = t.id) = 0 \n" +
"UNION\n" +
"SELECT \n" +
"r.id,\n" +
"' ' as chofer,\n" +
"if(ISNULL(t.id) , \"\", CONCAT(t.economic_number, ' - ', v.name)) as taxi,\n" +
"DATE(r.start_date) as fecha_inicial,\n" +
"DATE(r.end_date) as fecha_final,\n" +
"totalDaysInARangeOfDates(r.start_date, CURDATE(), TRUE),\n" +
"IF(ISNULL( \n" +
"(select GROUP_CONCAT(concat(' ',srvc.name)) from CONTRACT cntrct inner join CONTRACT_HAS_SERVICE chs on cntrct.id = chs.contract_id inner join SERVICE srvc on chs.service_id = srvc.id where cntrct.taxi_id = t.id and cntrct.active = 1) \n" +
") ,'', \n" +
"(select GROUP_CONCAT(concat(' ',srvc.name)) from CONTRACT cntrct inner join CONTRACT_HAS_SERVICE chs on cntrct.id = chs.contract_id inner join SERVICE srvc on chs.service_id = srvc.id where cntrct.taxi_id = t.id and cntrct.active = 1) \n" +
") AS contract_service, \n" +
"IF(ISNULL(c.ID) , \"\", CONCAT(c.first_name, ' ', c.last_name)) as cliente, \n" +
"totalDaysInARangeOfDates(STR_TO_DATE(:starDate, '%Y-%m-%d'), STR_TO_DATE(:endDate,'%Y-%m-%d'), TRUE) as num_days_dates \n" +
"FROM RELEASE_RESOURCE r \n" +
"INNER JOIN TAXI t ON t.id = r.taxi_id \n" +
"INNER JOIN VEHICLE v ON t.vehicle_id = v.id \n" + 
"INNER JOIN PERSON c ON t.customer_id = c.id \n" + 
"WHERE t.active = 1 AND t.id_location = :location AND (DATE(r.start_date) < STR_TO_DATE(:starDate, '%Y-%m-%d') AND r.end_date is null) AND (SELECT COUNT(so.id) FROM SERVICE_ORDER so WHERE so.service_order_type IN ('PENDING','APPROVED','PROGRESS',"+
"'PASE_TALLER') AND so.taxi_id = t.id) = 0 ";
    
}
