package com.fp.general.security.rules;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.SQLQuery;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;

import com.fp.common.exception.ExceptionHandler;
import com.fp.common.logger.APPLogger;
import com.fp.dto.Response;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pgeneral.gene.TgeneParameters;
import com.fp.persistence.pgeneral.gene.TgeneParametersKey;

/**
 * Clase que devuelve las companias
 * 
 * @author scastillo
 */
public class Company extends QueryRule {

    private static final String SQL =
            "select tgc.COMPANYCODE value,"
            + "       (select tcp.NAME"
            + "          from TCUSTPERSONDETAIL tcp"
            + "         where tcp.PERSONCODE = tgc.PERSONCODE"
            + "           and tcp.DATETO = :dateto) label"
            + "  from TGENECOMPANY tgc"
            + " where tgc.ACTIVE = :active";

    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        Response response = pQueryRequest.getResponse();
        try {
        	if(pQueryRequest.isJsf()){
        		response.put("CIAS", this.getCompanyJsf());
        	}else{
        		response.put("T", this.getCompany());	
        	}
        		
            
        } catch (Exception e) {
            ExceptionHandler eh = new ExceptionHandler(e, "es");
            APPLogger.getLogger().error("User Message:==>\n" + eh.getUserMessage());
            APPLogger.getLogger().error("Tech Message:==>\n" + eh.getTechnicalMessage());
            APPLogger.getLogger().error("Stack Message:==>\n" + eh.getStackTrace());
        }

        return pQueryRequest;
    }

    /**
     * Metodo que asigna la data de companias en un map
     * @return
     * @throws Exception
     */
    private List<Map<String, Object>> getCompany() 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>();
                Integer company = (Integer) obj[0];
                String companyname = (String) obj[1];
                mData.put("value", company);
                mData.put("label", companyname);
                TgeneParametersKey tgeneParametersKey = new TgeneParametersKey("JSVERSION", company);
                TgeneParameters tgeneParameters = TgeneParameters.find(PersistenceHelper.getEntityManager(),
                        tgeneParametersKey);
                if (tgeneParameters != null && tgeneParameters.getNumbervalue() != null) {
                    mData.put("vd", tgeneParameters.getNumbervalue().intValue());
                } else {
                    mData.put("vd", 0);
                }
                tgeneParametersKey = new TgeneParametersKey("LOGO", company);
                tgeneParameters = TgeneParameters.find(PersistenceHelper.getEntityManager(),
                        tgeneParametersKey);
                if (tgeneParameters != null && tgeneParameters.getTextvalue() != null) {
                    mData.put("lo", tgeneParameters.getTextvalue());
                } else {
                    mData.put("lo", "images/company/default.gif");
                }
                tgeneParametersKey = new TgeneParametersKey("FORMATDATE", company);
                tgeneParameters = TgeneParameters.find(PersistenceHelper.getEntityManager(),
                        tgeneParametersKey);
                if (tgeneParameters != null && tgeneParameters.getTextvalue() != null) {
                    mData.put("fd", tgeneParameters.getTextvalue());
                } else {
                    mData.put("fd", "yyyy-MM-dd");
                }
                tgeneParametersKey = new TgeneParametersKey("IMGFONDO", company);
                tgeneParameters = TgeneParameters.find(PersistenceHelper.getEntityManager(),
                        tgeneParametersKey);
                if (tgeneParameters != null && tgeneParameters.getTextvalue() != null) {
                    mData.put("fi", tgeneParameters.getTextvalue());
                } else {
                    mData.put("fi", null);
                }
                tgeneParametersKey = new TgeneParametersKey("TOPMENU", company);
                tgeneParameters = TgeneParameters.find(PersistenceHelper.getEntityManager(),
                        tgeneParametersKey);
                if (tgeneParameters != null && tgeneParameters.getTextvalue() != null
                        && tgeneParameters.getTextvalue().compareTo("Y") == 0) {
                    mData.put("tm", "Y");
                } else {
                    mData.put("tm", "N");
                }
                tgeneParametersKey = new TgeneParametersKey("TIMEOUT", (Integer) obj[0]);
                tgeneParameters = TgeneParameters.find(PersistenceHelper.getEntityManager(),
                        tgeneParametersKey);
                if (tgeneParameters != null && tgeneParameters.getNumbervalue() != null) {
                    mData.put("to", tgeneParameters.getNumbervalue().intValue());
                } else {
                    mData.put("to", 600);
                }
                //Se adiciona todos los parametros por compania
                ldata.add(mData);
            }
        } finally {
            if (rSet != null ) {
            	try {
            		rSet.close();	
				} catch (Exception e) {
					//Si el rset esta cerrado no hacer nada.
				}
                
            }
        }
        return ldata;
    }

    /**
     * Metodo que asigna la data de companias en un map
     * @return
     * @throws Exception
     */
    private List<Map<String, Object>> getCompanyJsf() 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>();
                Integer company = (Integer) obj[0];
                String companyname = (String) obj[1];
                mData.put("company", company);
                mData.put("name", companyname);
                //Se adiciona todos los parametros por compania
                ldata.add(mData);
            }
        } finally {
            if (rSet != null ) {
            	try {
            		rSet.close();	
				} catch (Exception e) {
					//Si el rset esta cerrado no hacer nada.
				}
                
            }
        }
        return ldata;
    }


    
    /**
     * Metodo que ejecuta el query para obtener el codigo y nombre de las companias
     *
     * @param pQueryRequest
     * @return
     * @throws Exception
     */
    private ScrollableResults executeQuery() throws Exception {
        ScrollableResults rSet = null;
        SQLQuery sql = PersistenceHelper.getSession().createSQLQuery(Company.SQL);
        sql.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
        sql.setParameter("active", "Y");
        sql.addScalar("value", new org.hibernate.type.IntegerType());
        sql.addScalar("label", new org.hibernate.type.StringType());
        
        rSet = sql.scroll(ScrollMode.FORWARD_ONLY);
        return rSet;
    }
}
