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

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.helper.MessageHelper;
import com.fp.persistence.pgeneral.safe.TsafeAuditInsDel;

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

    private static final long serialVersionUID = 1L;

    public AuditInsDelController() throws Exception {
        super(TsafeAuditInsDel.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 = 5; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "SAUDITINSDEL";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    public DtoQuery getDtoAuditInsDel() throws Exception {
        //super.addFilterDateto();

        DtoQuery dto = super.getDtoQuery(true);
        dto.setOrderby("t.pk.changedate");

        //subquery
        SubQuery subqueryBranch = new SubQuery("TgeneBranch", "description", "branchdesc",
                "i.pk.branchcode = t.branchcode and i.pk.companycode = t.companycode and i.pk.companycode="
                + super.getLoginController().getRequest().getCompany().toString());
        dto.addSubQuery(subqueryBranch);

        SubQuery subqueryOffice = new SubQuery("TgeneOffice", "description", "officedesc",
                "i.pk.officecode = t.officecode and i.pk.branchcode = t.branchcode and i.pk.companycode = t.companycode and i.pk.companycode="
                + super.getLoginController().getRequest().getCompany().toString());
        dto.addSubQuery(subqueryOffice);

        SubQuery subqueryPerson = new SubQuery("TcustPersonDetail", "name", "personname",
                "i.pk.personcode = t.personcode and i.pk.dateto = to_date('2999-12-31', 'yyyy-MM-dd') and i.companycode = t.companycode and i.companycode="
                + super.getLoginController().getRequest().getCompany().toString());
        dto.addSubQuery(subqueryPerson);

        SubQuery subqueryTransaction = new SubQuery("TgeneTransaction", "name", "transactiondesc",
                "i.pk.transactioncode = t.transactioncode and i.pk.transactionmodule = t.transactionmodule");
        dto.addSubQuery(subqueryTransaction);
        //subquery

        return dto;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            Request request = this.callerhelper.getRequest();
            DtoQuery dto = this.getDtoAuditInsDel();

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

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

    /**
     * Controla la respuesta de la consulta
     *
     * @param resp Objeto Response
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public void manageResponseAudit(Response resp) throws Exception {
        if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
            this.lrecord = null;
            MessageHelper.setMessageError(resp);
        } else {
            this.lrecord = (List<TsafeAuditInsDel>) resp.get(this.beanalias);

            super.postQuery(this.lrecord);
        }
    }

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

}
