package com.fp.frontend.controller.pcustomer;

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import com.fp.dto.AbstractDataTransport;
import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.query.SubQuery;
import com.fp.dto.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import java.sql.Timestamp;
import javax.persistence.Query;

/**
 * Clase controladora del bean TcustPersonDetail.
 *
 * @author Jorge Vaca.
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class PersonDetailController extends AbstractController<TcustPersonDetail> {

    private static final long serialVersionUID = 1L;

    public PersonDetailController() throws Exception {
        super(TcustPersonDetail.class);
    }

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
    }

    /**
     * Incializa el controlador, cuando se esta utilizando una pagina que utliza el controlador.
     */
    private void init() {
        try {
            recperpage = 10; // Cambiar al # reg a mirar.
            lrecord = new ArrayList<>();
            super.create();
            beanalias = "TCUSTPERSONDETAIL";

        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Agrega un par&acute;metro para la conulta
     *
     * @param personcode C&oacute;digo de persona
     */
    public void addPersoncodeFilter(String personcode) {
        super.addFilter("pk.personcode", personcode);
        record.getPk().setPersoncode(Integer.parseInt(personcode));
    }

    /**
     * M&eacute;todo para procesar la consulta
     *
     * @return dto Objeto DtoQuery
     * @throws Exception
     */
    public DtoQuery getDtoQuery() throws Exception {
        super.addFilterDateto();

        DtoQuery dto = super.getDtoQuery(false);

        // subqueries
        SubQuery subquery = new SubQuery("TgeneActivity", "description", "activitydesc", "i.pk = t.activitycode");
        dto.addSubQuery(subquery);

        SubQuery subquery1 = new SubQuery("TgeneActivity", "segmenttypecatalog", "segmenttypecatalog", "i.pk = t.activitycode");
        dto.addSubQuery(subquery1);

        SubQuery subquery2 = new SubQuery("TgeneCatalogDetail", "description", "segmentdesc",
                "i.pk.catalogcode = 'SEGMENTTYPE' and i.pk.catalog = (select a.segmenttypecatalog from TgeneActivity a where a.pk = t.activitycode)");
        dto.addSubQuery(subquery2);

        SubQuery subqueryTipoIdentificacion = new SubQuery("TgeneCatalogDetail", "description", "destipoidentificacion", "i.pk.catalog = t.identificationcatalog and  i.pk.catalogcode=t.identificationcatalogcode");
        dto.addSubQuery(subqueryTipoIdentificacion);
        return dto;
    }

    @Override
    protected void querydatabase() {
        try {
            Request request = callerhelper.getRequest();

            DtoQuery dto = this.getDtoQuery();

            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(beanalias, dto); // permite adicionar mas de una tabla.

            request.setQueryTables(mtables);

            Response resp = callerhelper.executeQuery(request);
            this.manageResponsePerson(resp);

        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    protected void querydatabaseAll() {
        try {
            DtoQuery dto = super.getDtoQuery(true);
            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(beanalias, dto); // permite adicionar mas de una tabla.
            SubQuery subqueryTipoIdentificacion = new SubQuery("TgeneCatalogDetail", "description", "destipoidentificacion", "i.pk.catalog = t.identificationcatalog and  i.pk.catalogcode=t.identificationcatalogcode");
            dto.addSubQuery(subqueryTipoIdentificacion);
            Request request = callerhelper.getRequest();
            request.setQueryTables(mtables);

            Response resp = callerhelper.executeQuery(request);

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                lrecord = new ArrayList<TcustPersonDetail>();
                MessageHelper.setMessageError(resp);
            } else {
                lrecord = (List<TcustPersonDetail>) resp.get(beanalias);
                super.postQuery(lrecord);
            }

        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Controla la respuesta de la consulta
     *
     * @param resp Objeto Response
     * @throws Exception
     */
    public void manageResponsePerson(Response resp) throws Exception {
        if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
            record = null;
            MessageHelper.setMessageError(resp);
        } else {
            record = (TcustPersonDetail) resp.get(beanalias);
            super.postQuery((AbstractDataTransport) resp.get(beanalias));
        }
    }

    @Override
    public void save() {
        try {
            Request request = callerhelper.getRequest();
            DtoSave dtosave = super.getDtoSave();
            if (!dtosave.pendingProcess()) {
                return;
            }
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();
            msave.put(beanalias, dtosave); // adicionar metadata de mantenimiento para cada tabla.

            request.setSaveTables(msave);
            Response resp = callerhelper.executeSave(request);
            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) == 0) {
                this.postCommit(resp);
                MessageHelper.setMessageInfo(resp);
            } else {
                MessageHelper.setMessageError(resp);
            }

        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void postCommit(Response response) throws Exception {
        super.postCommitGeneric(response, beanalias);
    }

    public static TcustPersonDetail find(String codigopersona) {
        try {
            PersonDetailController cc = new PersonDetailController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk.personcode", codigopersona);
            cc.addFilterDateto();
            cc.querydatabaseAll();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord.get(0);
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    /**
     * Autor Andres Cevallos
     *
     * @param identificacion
     * @param tipoidentificacion
     * @return Find para encontrar una persona por su identificacion y tipo de identificacion
     */
    public static TcustPersonDetail findxidentification(String identificacion, String tipoidentificacion) {
        try {
            PersonDetailController cc = new PersonDetailController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("identification", identificacion);
            cc.addFilter("identificationcatalog", tipoidentificacion);
            cc.addFilterDateto();
            cc.querydatabaseAll();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord.get(0);
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    public static TcustPersonDetail buscarLocal(String identificacion) {
        TcustPersonDetail detail = null;
        if (identificacion == null || identificacion.isEmpty() || identificacion.trim().length() < 10) {
            return detail;
        }
        try {
            String select = "select identificacion,id_rep_legal,rep_legal,nombre,razon_social,direccion,profesion,estado_civil,genero,descripcion"
                    + " from comaco.tmp_identificaciones where identificacion=:identificacion";
            Query query = PersistenceHelper.getEntityManager().createQuery(select);
            query.setParameter("identificacion", identificacion);
            List<Object[]> temp = query.getResultList();
            for (Object[] fila : temp) {
                detail = new TcustPersonDetail();
                detail.setIdentification((String) fila[0]);
                detail.setName(identificacion.length() == 13 ? (String) fila[4] : (String) fila[3]);
                detail.setIdentificationcatalog(identificacion.length() == 10 ? "CED" : "RUC");
                detail.setIdentificationcatalogcode("IDENTIFICATION");
                detail.setDatefrom(new Timestamp(System.currentTimeMillis()));
                break;
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
        return detail;
    }

    /**
     * @param identificacion
     * @param tipoidentificacion
     * @return Find para encontrar una persona por su identificacion
     */
    public static TcustPersonDetail findByIdentification(String identificacion) {
        try {
            PersonDetailController cc = new PersonDetailController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("identification", identificacion);
            cc.addFilterDateto();
            cc.querydatabaseAll();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord.get(0);
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

}
