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

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.fp.dto.query.QueryBean;
import com.fp.dto.query.QueryCriteria;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.GeneralQuery;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.APPDates;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pgeneral.safe.TsafeAuditInsDel;
import com.fp.persistence.pgeneral.safe.TsafeAuditInsDelKey;

/**
 * Clase que consulta los datos de la tabla TSAFEAUDITINSDEL
 *
 * @author BPTWPA
 *
 */
public class QueryAudit extends QueryRule {

    private static final long serialVersionUID = 1L;
    //SQL nativo para realizar la consulta
    private static final String SQL_AUDIT = "select t.changedate, t.tablename, t.realdate, t.terminalcode, "
            + "t.usercode, t.isinsert, t.account, t.solicitudenumber, t.personcode, "
            + "(select p.name from tcustpersondetail p where p.personcode=t.personcode "
            + "and p.dateto = :datetoperson) as name, "
            + "(select o.description from tgeneoffice o where o.officecode=t.officecode "
            + "and o.branchcode=t.branchcode and o.companycode=t.companycode) as officedesc, "
            + "(select b.description from tgenebranch b where b.branchcode=t.branchcode and "
            + "b.companycode=t.companycode) as branchdesc, "
            + "t.transactionmodule, t.transactioncode, t.transactionversion, "
            + "(select r.name from tgenetransaction r where r.transactionmodule=t.transactionmodule "
            + "and r.transactioncode=t.transactioncode and r.transactionversion=t.transactionversion) as transactiondesc "
            + ", t.partitiondb "
            + "from TSAFEAUDITINSDEL t "
            + "where t.changedate=t.changedate ";

    @Override
    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        StringBuilder sql = new StringBuilder();
        List<Object> listResp = new ArrayList<Object>();
        QueryBean qb = (QueryBean) pQueryRequest.get("TSAFEAUDITINSDEL");
        List<QueryCriteria> lcriteria = qb.getCriteria();
        sql.append(QueryAudit.SQL_AUDIT);
        Query qry = PersistenceHelper.getEntityManager().createNativeQuery(QueryAudit.addSimpleCriteria(sql, lcriteria, qb));
        QueryAudit.setSimpleParameters(qry, qb.getCriteria());
        qry.setParameter("datetoperson", FormatDates.getDefaultExpiryTimestamp());
        qry.setFirstResult((qb.getPage() - 1) * qb.getPageSize());
        qry.setMaxResults(qb.getPageSize());
        @SuppressWarnings("unchecked")
        List<Object> list = qry.getResultList();
        if (!list.isEmpty()) {
            for (Object oj : list) {
                Map<String, Object> mapResp = new HashMap<String, Object>();
                Object[] obj = (Object[]) oj;
                mapResp.put("pk_changedate", obj[0]);
                mapResp.put("pk_tablename", obj[1]);
                mapResp.put("pk_realdate", obj[2]);
                mapResp.put("terminalcode", obj[3]);
                mapResp.put("usercode", obj[4]);
                mapResp.put("isinsert", ((String.valueOf(obj[5]).compareTo("Y") == 0) ? "INSERT" : "DELETE"));
                mapResp.put("account", obj[6]);
                mapResp.put("solicitudenumber", obj[7]);
                mapResp.put("personcode", obj[8]);
                mapResp.put("name", obj[9]);
                mapResp.put("officedesc", obj[10]);
                mapResp.put("branchdesc", obj[11]);
                mapResp.put("transactiondesc", "(" + String.valueOf(obj[12]) + "-" + String.valueOf(obj[13]) + ") " + String.valueOf(obj[15]));
                mapResp.put("recvalue", this.recValueAudit(obj[0], obj[1], obj[16], obj[2]));
                listResp.add(mapResp);
            }
        }
        pQueryRequest.getResponse().put("TSAFEAUDITINSDEL", listResp);
        return pQueryRequest;
    }

    /**
     * Metodo que agrega los parametros de una consulta sql
     *
     * @param sql Creado
     * @param lcriteria Criterios de consulta
     * @return String del jpql
     */
    private static String addSimpleCriteria(StringBuilder sql, List<QueryCriteria> lcriteria, QueryBean qb) {
        for (QueryCriteria obj : lcriteria) {
            if (obj.getValue() != null) {
                if (obj.getProperty().compareTo("enddate") == 0) {
                    sql.append(" and ").append(obj.getOperation()).append(":").append(obj.getProperty());
                } else {
                    sql.append(" and ").append(obj.getProperty()).append(" ").append(obj.getOperation()).append(" :").append(obj.getProperty().replace(".", ""));
                }
            }
        }
        boolean first = true;
        for (QueryCriteria order : qb.getOrder(true)) {
            if (first) {
                sql.append(" ORDER BY ");
            } else {
                sql.append(" asc, ");
            }
            sql.append(order.getProperty());
            first = false;
        }
        return String.valueOf(sql);
    }

    /**
     * Metodo que setea los parametros para la consulta
     *
     * @param qry Query
     * @param lcriteria Criterios de consluta
     * @throws Exception
     */
    private static void setSimpleParameters(Query qry, List<QueryCriteria> lcriteria) throws Exception {
        for (QueryCriteria obj : lcriteria) {
            if (obj.getValue() != null) {
                if (obj.getProperty().replace(".", "").compareTo("tpkchangedate") == 0 || obj.getProperty().compareTo("enddate") == 0) {
                    APPDates date = new APPDates(obj.getValue().toString());
                    qry.setParameter(obj.getProperty().replace(".", ""), date.getDate());
                } else if ((obj.getProperty().replace(".", "").compareTo("ttransactioncode") == 0) || (obj.getProperty().replace(".", "").compareTo("tpersoncode") == 0)) {
                    qry.setParameter(obj.getProperty().replace(".", ""), Integer.valueOf(obj.getValue().toString()));
                } else {
                    qry.setParameter(obj.getProperty().replace(".", ""), obj.getValue());
                }
            }
        }
    }

    /**
     * Metodo que consulta el atributo recvalue del objeto TsafeAuditInsDel
     *
     * @param changedate
     * @param tablename
     * @param partitiondb
     * @param realdate
     * @return recvalue
     * @throws Exception
     */
    private String recValueAudit(Object changedate, Object tablename, Object partitiondb, Object realdate) throws Exception {
        String recvalue = "";
        Timestamp change = (Timestamp) changedate;
        Timestamp real = (Timestamp) realdate;
        String table = (String) tablename;
        String partition = (String) partitiondb;
        TsafeAuditInsDel tsafeAuditInsDel = TsafeAuditInsDel.find(PersistenceHelper.getEntityManager(),
                new TsafeAuditInsDelKey(change, table, partition, real));
        if (tsafeAuditInsDel != null) {
            recvalue = tsafeAuditInsDel.getRecvalue().substring(0, 110);
        } else {
            recvalue = "";
        }
        return recvalue;
    }
}
