package com.fp.frontend.controller.pcustomer;

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

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.helper.MessageHelper;
import com.fp.persistence.pcustomer.people.TcustPeople;

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

    private static final long serialVersionUID = 1L;

    private String personcode;

    public PeopleController() throws Exception {
        super(TcustPeople.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 = "TCUSTPEOPLE";
        } 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) {
        this.personcode = personcode;
        super.addFilter("pk.personcode", personcode);
        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);

        // subqueries
        // SubQuery subquery = new SubQuery("TgeneChannels", "description", "chanelname", "i.pk = t.channelcode");
        // dto.addSubQuery(subquery);
        return dto;
    }

    @Override
    protected void querydatabase() {
        try {
            Request request = callerhelper.getRequest();
            super.addFilterDateto();
            DtoQuery dto = this.getDtoQuery();

            SubQuery subqueryprof = new SubQuery("TgeneCatalogDetail", "description", "nprofesion",
                    "i.pk.catalogcode = 'PROFESSION' and i.pk.catalog = t.professioncatalog");
            dto.addSubQuery(subqueryprof);

            SubQuery subqueryestciv = new SubQuery("TgeneCatalogDetail", "description", "nestcivil",
                    "i.pk.catalogcode = 'MARITALSTATUS' and i.pk.catalog = t.maritalstatuscatalog");
            dto.addSubQuery(subqueryestciv);

            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.manageResponsePeople(resp);

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

    /**
     * Controla la respuesta de la consulta
     *
     * @param resp Objeto Response
     * @throws Exception
     */
    public void manageResponsePeople(Response resp) throws Exception {
        if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
            record = null;
            MessageHelper.setMessageError(resp);
            return;
        } else {
            record = (TcustPeople) resp.get(beanalias);
            if (record == null) {
                super.create();
                record.getPk().setPersoncode(Integer.parseInt(personcode));
            }
        }
        if (record.getGender() != null && record.getGender().equals("M")) {
            record.modifiedData.put("ngenero", "MASCULINO");
        } else if (record.getGender() != null && record.getGender().equals("F")) {
            record.modifiedData.put("ngenero", "FEMENINO");
        }

        super.postQuery(record);
    }

    @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);
    }
}
