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.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.controller.pgeneral.gene.CatalogDetailController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pcustomer.company.TcustCompany;
import com.fp.persistence.pgeneral.gene.TgeneCatalogDetail;

/**
 * Clase controladora del bean TcustCompany
 *
 * @author MAV.
 * @version 1.0
 */
@ManagedBean
@ViewScoped
public class CompanyController extends AbstractController<TcustCompany> {

    private static final long serialVersionUID = 1L;

    private String personcode;

    /**
     * Atributo para la lista de objetos TgeneCatalogDetail de tipo de empresa
     *
     */
    private List<TgeneCatalogDetail> lbusinesstype;

    /**
     * Atributo para la lista de objetos TgeneCatalogDetail de clases de empresa
     */
    private List<TgeneCatalogDetail> lbussinesclass;

    /**
     * Atributo para la lista de objetos TgeneCatalogDetail de tipo de
     * institucion
     */
    private List<TgeneCatalogDetail> linstitutiontype;

    /**
     * Atributo para la lista de objetos TgeneCatalogDetail de estdo de
     * operatividad
     */
    private List<TgeneCatalogDetail> loperativestatus;

    public CompanyController() throws Exception {
        super(TcustCompany.class);
    }

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        this.lbusinesstype = CatalogDetailController.find("BUSINESSTYPE");
        this.lbussinesclass = CatalogDetailController.find("BUSINESSCLASS");
        this.linstitutiontype = CatalogDetailController.find("PERSONTYPE");
        this.loperativestatus = CatalogDetailController.find("OPERATIVESTATUS");
    }

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

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

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

        SubQuery institutiontype = new SubQuery(
                "TgeneCatalogDetail",
                "description",
                "institutiontypedesc",
                "i.pk.catalog = t.institutiontypecatalog and i.pk.catalogcode= 'INSTITUTIONTYPE' ");
        dto.addSubQuery(institutiontype);

        return dto;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            DtoQuery dto = getDtoQuery(true);

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

            Request request = this.callerhelper.getRequest();
            request.setQueryTables(mtables);

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

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                lrecord = new ArrayList<TcustCompany>();
                MessageHelper.setMessageError(resp);
            } else {
                lrecord = (List<TcustCompany>) resp.get(beanalias);
                if (lrecord != null && !lrecord.isEmpty()) {
                    record = lrecord.get(0);
                }
                super.postQuery(lrecord);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Controla la respuesta de la consulta
     *
     * @param resp Objeto Response
     * @throws Exception
     */
    public void manageResponseCompany(Response resp) throws Exception {
        if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
            this.record = null;
            MessageHelper.setMessageError(resp);
        } else {
            this.record = (TcustCompany) resp.get(this.beanalias);
            if (this.record == null) {
                super.create();
                this.record.getPk().setPersoncode(
                        Integer.parseInt(this.personcode));
            }
            super.postQuery(this.record);
        }
    }

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

            request.setSaveTables(msave);
            Response resp = this.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, this.beanalias);
    }

    /**
     * Busca una solicitud por su codigo
     *
     * @param codigoSolicitud
     * @return
     */
    public static TcustCompany findByPersonCode(String personCode) {
        try {
            CompanyController cc = new CompanyController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk.personcode", personCode);
            cc.addFilterDateto();
            cc.querydatabase();

            if (cc.record != null) {
                return cc.record;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    /**
     * @return the personcode
     */
    public String getPersoncode() {
        return personcode;
    }

    /**
     * @param personcode the personcode to set
     */
    public void setPersoncode(String personcode) {
        this.personcode = personcode;
    }

    /**
     * @return the lbusinesstype
     */
    public List<TgeneCatalogDetail> getLbusinesstype() {
        return lbusinesstype;
    }

    /**
     * @param lbusinesstype the lbusinesstype to set
     */
    public void setLbusinesstype(List<TgeneCatalogDetail> lbusinesstype) {
        this.lbusinesstype = lbusinesstype;
    }

    /**
     * @return the lbussinesclass
     */
    public List<TgeneCatalogDetail> getLbussinesclass() {
        return lbussinesclass;
    }

    /**
     * @param lbussinesclass the lbussinesclass to set
     */
    public void setLbussinesclass(List<TgeneCatalogDetail> lbussinesclass) {
        this.lbussinesclass = lbussinesclass;
    }

    /**
     * @return the linstitutiontype
     */
    public List<TgeneCatalogDetail> getLinstitutiontype() {
        return linstitutiontype;
    }

    /**
     * @param linstitutiontype the linstitutiontype to set
     */
    public void setLinstitutiontype(List<TgeneCatalogDetail> linstitutiontype) {
        this.linstitutiontype = linstitutiontype;
    }

    /**
     * @return the loperativestatus
     */
    public List<TgeneCatalogDetail> getLoperativestatus() {
        return loperativestatus;
    }

    /**
     * @param loperativestatus the loperativestatus to set
     */
    public void setLoperativestatus(List<TgeneCatalogDetail> loperativestatus) {
        this.loperativestatus = loperativestatus;
    }

}
