package com.fp.frontend.controller.bpm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
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.common.properties.PropertiesHandler;
import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.controller.bpm.lov.TransactionBpmELovController;
import com.fp.frontend.controller.pgeneral.date.TgeneAccountingDateBranchController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.log.TgeneTransactionLog;

/**
 * Clase controladora del bean TgeneTransactionLog.
 *
 * @author WPA
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class EndedFlowsController extends AbstractController<TgeneTransactionLog> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public EndedFlowsController() throws Exception {
        super(TgeneTransactionLog.class);
    }

    /**
     * Atributo para la lista de objetos del QueryAlias
     */
    private List<Map<String, Object>> ltransactionlog;

    /**
     * Atributo para la lista de objetos del QueryAlias
     */
    private List<Map<String, Object>> ltbpmactivities;

    /**
     * Atributo para obtener los datos del query
     */
    private Map<String, Object> recordmap;

    /**
     * Atributo para el detalle de la actividad realizada
     */
    private Map<String, Object> activityDetail;

    /**
     * Atributo para el filtro de fecha desde
     */
    private Date fromdate;

    /**
     * Atributo para el filtro de fecha hasta
     */
    private Date todate;

    @PostConstruct
    private void postconstruct() {
        this.init();
        // this.initDates();
        // 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.lrecord = new ArrayList<>();
            this.beanalias = "TRANSACTIONLOG";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            if (super.getMfilters().get("transactionmodule") == null) {
                MessageHelper.setMessageError("msg_catalogrequird");
                return;
            }

            Request request = this.callerhelper.getRequest();
            DtoQuery dto = super.getDtoQuery(true);

            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(this.beanalias, dto); // permite adicionar mas de una tabla.
            request.setQueryTables(mtables);
            request.put("querytype", "P");
            request.put("creationdate", this.fromdate);
            request.put("enddate", this.todate);
            request.put("queryalias", "ENDEDFLOWS");

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

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.ltransactionlog = new ArrayList<Map<String, Object>>();
                MessageHelper.setMessageError(resp);
            } else {
                this.ltransactionlog = (List<Map<String, Object>>) resp.get(this.beanalias);
            }

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

    @Override
    public void save() {
        MessageHelper.setMessageError("msg_notSave");
    }

    /**
     * Abre el lov de transacciones
     */
    public void openTransactionLov() {
        Map<String, List<String>> params = new HashMap<>();
        List<String> l = new ArrayList<>();
        l.add("TRANSACTION"); // valor del parametro
        params.put("processtype", l);

        TransactionBpmELovController.openLov(params);
    }

    /**
     * Gestiona la respuesta del lov
     *
     * @param event
     * @throws Exception
     */
    public void onReturnTransactionLov(SelectEvent event) throws Exception {

        Object obj = event.getObject();
        Map<String, Object> t = (Map<String, Object>) obj;
        super.addFilter("transactionmodule", String.valueOf(t.get("pk_transactionmodule")));
        super.addFilter("transactioncode", String.valueOf(t.get("pk_transactioncode")));
        super.addFilter("transactionversion", String.valueOf(t.get("pk_transactionversion")));
        super.addField("transactionname", String.valueOf(t.get("name")));
        // this.query();
    }

    /**
     * Inicializa las fechas
     */
    public void initDates() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(this.getWorkingDate());
        this.todate = calendar.getTime();
        calendar.add(Calendar.YEAR, -1);
        calendar.add(Calendar.DATE, -1);
        this.fromdate = calendar.getTime();
    }

    /**
     * Entrega la fecha de trabajo de la aplicacin.
     *
     * @return Fecah Fecha de trabajo.
     * @throws Exception
     */
    public 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;
    }

    /**
     * Entrega la fecha en String
     *
     * @param fecha Date
     * @return Fecha en String
     */
    public String dateToString(Date fecha) {
        String formato = "";
        try {
            PropertiesHandler ph = new PropertiesHandler("general_es");
            formato = ph.getStringValue("dateformat");
        } catch (Exception e) {
            // nothing
        }
        SimpleDateFormat date = new SimpleDateFormat(formato);
        return date.format(fecha);
    }

    /**
     * Consulta el detalle de los flujos
     */
    public void queryRequestDetail() {
        try {
            Request request = this.callerhelper.getRequest();
            DtoQuery dto = new DtoQuery("com.fp.persistence.pbpm.gene.TbpmActivities", this.page, 20, true, new HashMap<String, String>());

            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put("TBPMACTIVITIES", dto);
            request.setQueryTables(mtables);
            request.put("querytype", "P");
            request.put("queryalias", "FLOWDETAIL");
            System.out.println("JOURNAL IDDDDDD " + this.recordmap.get("id"));
            request.put("ID", this.recordmap.get("id"));

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

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.ltbpmactivities = new ArrayList<Map<String, Object>>();
                MessageHelper.setMessageError(resp);
            } else {
                this.ltbpmactivities = (List<Map<String, Object>>) resp.get("TBPMACTIVITIES");
            }

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

    /**
     * Entrega una lista de objetos
     *
     * @return ltransactionlog Lista de objetos
     */
    public List<Map<String, Object>> getLtransactionlog() {
        return ltransactionlog;
    }

    /**
     * Fija una lista de objetos
     *
     * @aram ltransactionlog Lista de objetos
     */
    public void setLtransactionlog(List<Map<String, Object>> ltransactionlog) {
        this.ltransactionlog = ltransactionlog;
    }

    /**
     * Entrega el ojbeto Date
     *
     * @return fromdate
     */
    public Date getFromdate() {
        return fromdate;
    }

    /**
     * Fija el ojbeto Date
     *
     * @param fromdate
     */
    public void setFromdate(Date fromdate) {
        this.fromdate = fromdate;
    }

    /**
     * Entrega el ojbeto Date
     *
     * @return todate
     */
    public Date getTodate() {
        return todate;
    }

    /**
     * Fija el ojbeto Date
     *
     * @param todate
     */
    public void setTodate(Date todate) {
        this.todate = todate;
    }

    /**
     * Entrega un Map<String, Object>
     *
     * @return recordmap
     */
    public Map<String, Object> getRecordmap() {
        return recordmap;
    }

    /**
     * Fija un Map<String, Object>
     *
     * @param recordmap
     */
    public void setRecordmap(Map<String, Object> recordmap) {
        this.recordmap = recordmap;
    }

    /**
     * Entrega una list de Map<String, Object> con las actividades del flujo
     *
     * @return ltbpmactivities
     */
    public List<Map<String, Object>> getLtbpmactivities() {
        return ltbpmactivities;
    }

    /**
     * Fija una list de Map<String, Object> con las actividades del flujo
     *
     * @param ltbpmactivities
     */
    public void setLtbpmactivities(List<Map<String, Object>> ltbpmactivities) {
        this.ltbpmactivities = ltbpmactivities;
    }

    /**
     * Entrega un mapa activityDetail
     *
     * @return activityDetail
     */
    public Map<String, Object> getActivityDetail() {
        return activityDetail;
    }

    /**
     * Fija un mapa activityDetail
     *
     * @param activityDetail
     */
    public void setActivityDetail(Map<String, Object> activityDetail) {
        this.activityDetail = activityDetail;
    }

}
