package com.fp.frontend.controller.pcustomer;

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

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

import org.primefaces.event.SelectEvent;

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.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.controller.pcustomer.lov.PersonLovController;
import com.fp.frontend.controller.pgeneral.gene.CatalogDetailController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pbpm.gene.TbpmGroups;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pgeneral.gene.TgeneCatalogDetail;

/**
 * Clase controladora del bean TsafeUserDetail.
 *
 * @author Andres E. Carpio
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class PersonViewController extends AbstractController<TcustPersonDetail> {

    private static final long serialVersionUID = 1L;

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

    @ManagedProperty(value = "#{peopleController}")
    private PeopleController people;

    /**
     * Atributo para la lista de objetos TgeneCatalogDetail de identificacion
     */
    private List<TgeneCatalogDetail> lidentification;

    /**
     * Atributo para el listado de g&eacute;neros
     */
    private List<String[]> lgender;

    /**
     * Atributo para activar el keyFilter
     */
    private boolean activeRegEx;
    /**
     * Atributo para la longitud de la identificaci&oacute;n
     */
    private String lengthId;

    @PostConstruct
    private void postconstruct() {
        this.lengthId = "10";
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        //List
        this.lidentification = CatalogDetailController.find("IDENTIFICATION", "1");
        this.lgender = CatalogDetailController.getListGender();

    }

    /**
     * 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.create();
            this.lrecord = new ArrayList<>();
            this.beanalias = "TCUSTPERSONDETAIL";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            if (super.getMfilters().get("sbsemployee") == null) {
                MessageHelper.setMessageError("msg_filterrequird");
                return;
            }
            super.addFilterDateto();
            Request request = this.callerhelper.getRequest();
            DtoQuery dto = super.getDtoQuery(false);
            dto.setOrderby("t.pk.personcode");

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

            request.setQueryTables(mtables);

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

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.create();
                //this.record = new TcustPersonDetail();
                MessageHelper.setMessageError(resp);
            } else {
                this.record = (TcustPersonDetail) resp.get(this.beanalias);
                if (this.record != null) {
                    this.people.addPersoncodeFilter(this.record.getPk().getPersoncode().toString());
                    this.people.query();
                } else {
                    this.create();
                }
                super.postQuery(this.record);
            }

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

    @Override
    public void save() {
        try {
            Request request = this.callerhelper.getRequest();
            this.update();
            this.people.update();

            DtoSave dtoSave = super.getDtoSave(true);
            DtoSave dtoSavePeople = this.people.getDtoSave(true);

            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();

            if (dtoSave.pendingProcess()) {
                msave.put(this.beanalias, dtoSave);
            }

            if (dtoSavePeople.pendingProcess()) {
                msave.put(this.people.getBeanalias(), dtoSavePeople);
            }

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

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

    /**
     * Cambio del ID
     */
    public void onChangeId() {
        if (this.record.getIdentificationcatalog().compareTo("CED") == 0) {
            this.lengthId = "10";
            this.activeRegEx = false;
        } else if (this.record.getIdentificationcatalog().compareTo("PAS") == 0) {
            this.lengthId = "13";
            this.activeRegEx = true;
        }
    }

    /**
     * Abre el lob de empleados sbs
     */
    public void openPersonViewLov() {
        Map<String, List<String>> params = new HashMap<>();
        PersonViewLovController.openLov(params);
    }

    /**
     * Maneja la respuesta del lov de empleados sbs
     *
     * @param event
     * @throws Exception
     */
    public void onReturnPersonViewLov(SelectEvent event) throws Exception {
        Object[] t = (Object[]) event.getObject();
        super.addFilter("sbsemployee", (String) t[0]);
        super.addField("personname", (String) t[2] + " " + (String) t[1]);
        this.querydatabase();

        if (this.record.getPk().getPersoncode() == null) {
            this.record.setName((String) t[2] + " " + (String) t[1]);
            this.record.setIdentification((String) t[4]);
            this.record.setSbsemployee((String) t[0]);
            this.record.setSbsusercode((String) t[3]);
            this.record.setIdentificationcatalogcode("IDENTIFICATION");
            this.people.getRecord().setFirstname(this.getName((String) t[2], true));;
            this.people.getRecord().setMiddlename(this.getName((String) t[2], false));
            this.people.getRecord().setLastname(this.getName((String) t[1], true));
            this.people.getRecord().setSurename(this.getName((String) t[1], false));
        }

    }

    /**
     * Arma el nombre del funcionario
     *
     * @param firstname nombre
     * @param first	v/f
     * @return name
     */
    public String getName(String firstname, boolean first) {
        String[] value = firstname.split(" ");
        String name = "";
        for (int i = 0; i < value.length; i++) {
            if (i == 0 && first) {
                name = value[i];
            } else if (i > 0 && !first) {
                name = name + ((name.length() == 0) ? "" : " ") + value[i];
            }
        }
        return name;
    }

    /**
     * Entrega Verdadero/Falso
     *
     * @return activeNotEconomic V/F
     */
    public boolean isActiveRegEx() {
        return this.activeRegEx;
    }

    /**
     * Fija Verdadero/Falso
     *
     * @param activeNotEconomic V/F
     */
    public void setActiveRegEx(boolean activeRegEx) {
        this.activeRegEx = activeRegEx;
    }

    /**
     * Entrega el n&uacute;mero de digitos para el tipo de identificaci&oacuye;n
     *
     * @return lengthId N&uacute;mero de digitos
     */
    public String getLengthId() {
        return this.lengthId;
    }

    /**
     * Fija el n&uacute;mero de digitos para el tipo de identificaci&oacuye;n
     *
     * @param lengthId N&uacute;mero de digitos
     */
    public void setLengthId(String lengthId) {
        this.lengthId = lengthId;
    }

    /**
     * Entrega lista de objetos TgeneCatalogDetail tipo de identificaci&oacute;n
     *
     * @return lidentification Lista de objetos TgeneCatalogDetail
     */
    public List<TgeneCatalogDetail> getLidentification() {
        return this.lidentification;
    }

    /**
     * Fija lista de objetos TgeneCatalogDetail tipo de identificaci&oacute;n
     *
     * @param lidentification Lista de objetos TgeneCatalogDetail
     */
    public void setLidentification(List<TgeneCatalogDetail> lidentification) {
        this.lidentification = lidentification;
    }

    /**
     * Entrega la lista de g&eacute;neros
     *
     * @return lgender Lista de g&eacute;neros
     */
    public List<String[]> getLgender() {
        return this.lgender;
    }

    /**
     * Fija la lista de g&eacute;neros
     *
     * @param lgender Lista de g&eacute;neros
     */
    public void setLgender(List<String[]> lgender) {
        this.lgender = lgender;
    }

    /**
     * Entrega el valor de: persondetail
     *
     * @return PersonDetailController
     */
    public PeopleController getPeople() {
        return this.people;
    }

    /**
     * Fija el valor de: persondetail
     *
     * @param people Valor a fijar en el atributo.
     */
    public void setPeople(PeopleController people) {
        this.people = people;
    }
}
