package com.fp.general.rules.query.code;

import com.fp.dto.Response;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.general.exception.GeneralException;
import com.fp.persistence.commondb.PersistenceHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;

/**
 * Clase que se encarga de armar la estructura para la grilla para la generación de fechas contables
 * @author scastillo
 */
public class DaysAccountingDate extends QueryRule {

    private static final String SQL =
            "select TGC.LEGALCODE, TGC.DESCRIPTION"
            + "  from TGENECATALOGDETAIL TGC"
            + " where TGC.CATALOGCODE = 'DAYS'"
            + " order BY TGC.CATALOG";

    /**
     * Metodo que se encarga de armar el map
     * @param queryRequest
     * @return
     * @throws Exception
     */
    public QueryRequest process(QueryRequest queryRequest) throws Exception {
        Response response = queryRequest.getResponse();
        response.put("branchcodemin", this.getBranchMin(queryRequest.getCompany()));
        response.put("branchcodemax", this.getBranchMax(queryRequest.getCompany()));
        response.put("LISTACCOUNTINDATE", this.getDays());
        return queryRequest;
    }

    /**
     * Metodo que arma la estructura para situarla en el datagrid
     * @return
     * @throws Exception
     */
    private List<Map<String, Object>> getDays() throws Exception {
        ScrollableResults rSet = null;
        List<Map<String, Object>> ldata = new ArrayList<Map<String, Object>>();
        try {
            rSet = this.executeQuery();
            while (rSet.next()) {
                Object[] obj = rSet.get();
                Map<String, Object> mData = new HashMap<String, Object>();
                mData.put("transportBeanClass", null);
                mData.put("day", obj[0]);
                mData.put("daydesc", obj[1]);
                mData.put("accounting", "N");
                mData.put("teller", "N");
                ldata.add(mData);
            }
        } finally {
            if (rSet != null) {
                rSet.close();
            }
        }
        return ldata;
    }

    /**
     * Metodo que ejecuta para obtener los dias
     * @param pQueryRequest
     * @return
     * @throws Exception
     */
    private ScrollableResults executeQuery() throws Exception {
        ScrollableResults rSet = null;
        SQLQuery sql = PersistenceHelper.getSession().createSQLQuery(SQL);
        rSet = sql.scroll();
        return rSet;
    }
    private static String SQL_BRANCH_MIN =
            "select min(BRANCHCODE) value"
            + "  from TGENEBRANCH"
            + " where COMPANYCODE = :companycode";

    /**
     * Metodo que devuelve el codigo de sucursal menor
     * @param companycode
     * @return
     * @throws Exception
     */
    private Integer getBranchMin(Integer companycode) throws Exception {
        SQLQuery sql = PersistenceHelper.getSession().createSQLQuery(SQL_BRANCH_MIN);
        sql.setParameter("companycode", companycode);
        sql.addScalar("value", new org.hibernate.type.IntegerType());
        Integer value = (Integer) sql.uniqueResult();
        if (value == null) {
            throw new GeneralException("GENE-0018", "SUCURSALES NO DEFINIDAS PARA LA COMPANIA: {0}", companycode);
        }
        return value;
    }
    /**
    Sentencia SQL que devuelve la sucursal mayor
     */
    private static String SQL_BRANCH_MAX =
            "select max(BRANCHCODE) value"
            + "  from TGENEBRANCH"
            + " where COMPANYCODE = :companycode";

    /**
     * Metodo que devuelve el codigo de sucursal maxima
     * @param companycode
     * @return
     * @throws Exception
     */
    private Integer getBranchMax(Integer companycode) throws Exception {
        SQLQuery sql = PersistenceHelper.getSession().createSQLQuery(SQL_BRANCH_MAX);
        sql.setParameter("companycode", companycode);
        sql.addScalar("value", new org.hibernate.type.IntegerType());
        Integer value = (Integer) sql.uniqueResult();
        if (value == null) {
            throw new GeneralException("GENE-0018", "SUCURSALES NO DEFINIDAS PARA LA COMPANIA: {0}", companycode);
        }
        return value;
    }
}
