package com.fp.frontend.controller.bpm;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
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.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.pgeneral.date.TgeneAccountingDateBranchController;
import com.fp.frontend.controller.pgeneral.gene.CatalogDetailController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.commondb.helper.APPDates;
import com.fp.persistence.pbpm.gene.TbpmNotify;
import com.fp.persistence.pgeneral.gene.TgeneCatalogDetail;

/**
 * Clase controladora del bean TbpmNotify.
 *
 * @author WPA.
 * @version 2.1
 */
@SuppressWarnings("serial")
@ManagedBean
@ViewScoped
public class NotifyController extends AbstractController<TbpmNotify> {

    /**
     * Constructor
     *
     * @throws Exception
     */
    public NotifyController() throws Exception {
        super(TbpmNotify.class);
    }

    /**
     * Atributo para la lista de catalogos
     */
    private List<TgeneCatalogDetail> lcatalog;

    /**
     * Metodo invocado despues de instanciar el controlador
     */
    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        //Lista
        this.lcatalog = CatalogDetailController.find("NOTIFYTOCATALOG");
    }

    /**
     * Incializa variables del controlador, cuando se esta utilizando una pagina
     * que utliza el controlador.
     */
    private void init() {
        try {
            this.recperpage = 10; // Cambiar al # reg a mirar.
            super.create();
            super.record.setNotifytocatalogcode("NOTIFYTOCATALOG");
            super.record.setRegisterdate(new Timestamp(this.getWorkingDate().getTime()));
            super.record.setUserwhoreg(super.getLoginController().getRequest().getUser());
            this.lrecord = new ArrayList<>();
            this.beanalias = "TBPMNOTIFY";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Entrega la fecha de trabajo de la aplicacin.
     *
     * @return Fecah Fecha de trabajo.
     */
    private Date getWorkingDate() {
        Date workingDate = null;
        try {
            TgeneAccountingDateBranchController c = new TgeneAccountingDateBranchController();
            c.getMfilters().clear();
            c.getMfilters().put("pk.branchcode", "0");
            c.getMfilters().put("pk.companycode", super.getLoginController().getRequest().getCompany().toString());
            c.query();
            workingDate = c.getRecord().getWorkingdate();
        } catch (Exception ex) {
            //
        }
        return workingDate;
    }

    /* (non-Javadoc)
	 * @see com.fp.frontend.controller.AbstractController#querydatabase()
     */
    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            Request request = this.callerhelper.getRequest();
            DtoQuery dto = super.getDtoQuery(false);
            dto.setOrderby("t.pk"); // En en string van todos los campos de orden ("t.pk,  t.nombre, t.cpais").

            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 = new TbpmNotify();
                MessageHelper.setMessageError(resp);
            } else {
                this.record = (TbpmNotify) resp.get(this.beanalias);
                if (this.record != null) {
                    super.postQuery((AbstractDataTransport) resp.get(this.beanalias));
                } else {
                    this.create();
                }
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /* (non-Javadoc)
	 * @see com.fp.frontend.controller.AbstractController#save()
     */
    @Override
    public void save() {
        try {
            Request request = this.callerhelper.getRequest();
            this.update();
            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);
        }
    }

    /**
     * Entrega la lista de objetos TgeneCatalogDetail
     *
     * @return lcatalog
     */
    public List<TgeneCatalogDetail> getLcatalog() {
        return lcatalog;
    }

    /**
     * Fija la lista de objetos TgeneCatalogDetail
     *
     * @param lcatalog
     */
    public void setLcatalog(List<TgeneCatalogDetail> lcatalog) {
        this.lcatalog = lcatalog;
    }

}
