package com.fp.frontend.controller.pgeneral.safe;

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.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.query.SubQuery;
import com.fp.dto.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.controller.pcustomer.lov.PersonLovController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.parmas.fun.TarmRegistroArmas;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pgeneral.safe.TsafeUserDetail;

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

    private static final long serialVersionUID = 1L;

    public UserDetailController() throws Exception {
        super(TsafeUserDetail.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 {
            this.recperpage = 10; // Cambiar al # reg a mirar.
            this.record = new TsafeUserDetail();
            this.lrecord = new ArrayList<>();
            this.beanalias = "USERDETAIL";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void create() throws Exception {
        super.create();
        if (this.getMfilters().get("pk.personcode") != null) {
            this.record.getPk().setPersoncode(Integer.valueOf(this.getMfilters().get("pk.personcode")));
        }
        this.record.setCompanycode(super.getLoginController().getRequest().getCompany());
        this.record.setUserstatuscatalogcode("USERSTATUS");
        this.record.setUserstatuscatalog("ENT");
        this.record.setChangepassword("Y");
    }

    @Override
    protected void querydatabase() {
        try {
            if (!super.existAtLeastOneFilterValue()) {
                MessageHelper.setMessageError("msg_filterrequird");
                return;
            }
            Request request = this.callerhelper.getRequest();
            super.addFilterDateto();
            super.addFilter("companycode", super.getLoginController().getRequest().getCompany()
                    .toString());
            DtoQuery dto = super.getDtoQuery(false);
            dto.setOrderby("t.pk"); // En en string van todos los campos de
            // orden ("t.pk,  t.nombre, t.cpais").

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

            SubQuery subquerya = new SubQuery("TgeneArea", "descripction", "areaname",
                    "i.pk.companycode = t.companycode and i.pk.areacode = t.areacode ");
            dto.addSubQuery(subquerya);

            SubQuery subquerys = new SubQuery("TgeneCatalogDetail", "description", "statusdesc",
                    "i.pk.catalogcode = t.userstatuscatalogcode and i.pk.catalog = t.userstatuscatalog ");
            dto.addSubQuery(subquerys);

            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.record = null;
                MessageHelper.setMessageError(resp);
            } else {
                this.manageresponse(resp);
            }

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

    private void manageresponse(Response resp) throws Exception {

        this.record = (TsafeUserDetail) resp.get(this.beanalias);
        if (this.record == null) {
            //si no existe crea un registro para permitir el ingreso.s
            this.create();
        } else {
            super.addFilter("pk.usercode", this.record.getPk().getUsercode());
            super.postQuery((AbstractDataTransport) resp.get(this.beanalias));
        }
        if ((super.getMfilelds().get("personname") == null)) {
            if ((super.getMfilters().get("pk.personcode") != null) || (this.record.getPk().getPersoncode() != null)) {
                String personcode = super.getMfilters().get("pk.personcode") != null ? super.getMfilters().get("pk.personcode") : this.record.getPk().getPersoncode().toString();
                TcustPersonDetail tcpd = PersonLovController.find(personcode);
                super.addField("personname", tcpd != null ? tcpd.getName() : "");
            }
        }
    }

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

    public void openPersonLov() {
        Map<String, List<String>> params = new HashMap<>();
        PersonLovController.openLov(params);
    }

    public void onReturnPersonLov(SelectEvent event) throws Exception {
        TcustPersonDetail t = (TcustPersonDetail) event.getObject();
        super.addFilter("pk.personcode", t.getPk().getPersoncode().toString());
        super.addField("personname", t.getName());
    }

    public void update(TsafeUserDetail bean) throws Exception {
        record = bean;
        update();
    }

}
