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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
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.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.pgeneral.gene.CatalogDetailController;
import com.fp.frontend.controller.pgeneral.lov.ProfileLovController;
import com.fp.frontend.controller.pgeneral.lov.TransactionLovController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.gene.TgeneCatalogDetail;
import com.fp.persistence.pgeneral.safe.TsafeProfile;
import com.fp.persistence.pgeneral.safe.TsafeProfileHorary;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;

/**
 * Clase controladora del bean TsafeProfileHorary.
 *
 * @author David L&oacute;pez P.
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class ProfileHoraryController extends AbstractController<TsafeProfileHorary> {

    private static final long serialVersionUID = 1L;

    private static SimpleDateFormat TIMEFORMAT = new SimpleDateFormat("HH:mm");

    private Date initTime;

    private Date endTime;

    private Date actualDate;

    public ProfileHoraryController() throws Exception {
        super(TsafeProfileHorary.class);
    }

    private List<TgeneCatalogDetail> tdays;

    @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.lrecord = new ArrayList<>();
            this.beanalias = "PHORARY";
            this.tdays = CatalogDetailController.find("DAYS");
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Crea una instancia de TsafeProfileHorary y marca el registro como nuevo.
     *
     * @throws Exception
     */
    @Override
    public void create() throws Exception {
        if (super.getMfilters().get("pk.transactionmodule") == null) {
            MessageHelper.setMessageError("msg_transactionrequird");
            return;
        }
        if (super.getMfilters().get("pk.profilecode") == null) {
            MessageHelper.setMessageError("msg_profilerequird");
            return;
        }
        super.create();
        this.record.getPk().setProfilecode(super.getMfilters().get("pk.profilecode"));
        this.record.getPk().setTransactionmodule(super.getMfilters().get("pk.transactionmodule"));
        this.record.getPk().setTransactioncode(Integer.valueOf(super.getMfilters().get("pk.transactioncode")));
        this.record.getPk().setTransactionversion(Integer.valueOf(super.getMfilters().get("pk.transactionversion")));
    }

    @Override
    public void update() throws Exception {
        if (record.getInittime().compareTo(record.getFinishtime()) > 0) {
            MessageHelper.setMessageError("msg_validatetimehour");
            return;
        }
        String registercode = record.getPk().getProfilecode() + record.getPk().getTransactionmodule() + record.getPk().getTransactioncode() + record.getPk().getTransactionversion() + record.getPk().getDay();
        if (record.getRegistercode() == null || !record.getRegistercode().equals(registercode)) {
            record.setRegistercode(registercode);
        }
        super.update();
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        if ((super.getMfilters().get("pk.transactionmodule") == null) || (super.getMfilters().get("pk.profilecode") == null)) {
            MessageHelper.setMessageError("msg_transactionrequird");
            return;
        }
        try {
            //super.addFilter("catalogtypeprocess", "REPORT");
            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.pk.profilecode");

            // subqueries
            SubQuery subquery = new SubQuery("TsafeProfile", "description", "descrip",
                    "i.pk = t.pk.profilecode");
            dto.addSubQuery(subquery);

            SubQuery subquery2 = new SubQuery("TgeneCatalogDetail", "description", "days",
                    "i.legalcode = t.pk.day  and i.pk.catalogcode='DAYS'");

            dto.addSubQuery(subquery);
            dto.addSubQuery(subquery2);

            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(this.beanalias, dto); // permite adicionar mas de una tabla.

            Request request = this.callerhelper.getRequest();
            request.setQueryTables(mtables);

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

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.lrecord = new ArrayList<TsafeProfileHorary>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TsafeProfileHorary>) resp.get(this.beanalias);
                super.postQuery(this.lrecord);
            }

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

    @Override
    public void save() {
        try {
            DtoSave dtosave = super.getDtoSave();
            dtosave.setReturnpk(true); // Para que el core devuelva el pk de los registros nuevos.
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();

            Request request = this.callerhelper.getRequest();
            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 openTransactionLov() {
        Map<String, List<String>> params = new HashMap<>();
        List<String> l = new ArrayList<>();
        l.add("TRANSACTION"); // valor del parametro
        params.put("processtype", l);
        TransactionLovController.openLov(params);
    }

    public void onReturnTransactionLov(SelectEvent event) throws Exception {
        TgeneTransaction t = (TgeneTransaction) event.getObject();
        super.addFilter("pk.transactionmodule", t.getPk().getTransactionmodule());
        super.addFilter("pk.transactioncode", t.getPk().getTransactioncode().toString());
        super.addFilter("pk.transactionversion", t.getPk().getTransactionversion().toString());
        super.addField("name", t.getName());

    }

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

    public void onReturnProfileLov(SelectEvent event) throws Exception {
        TsafeProfile t = (TsafeProfile) event.getObject();
        super.addFilter("pk.profilecode", t.getPk());
        super.addField("description", t.getDescription());

    }

    /**
     * Obtiene dias a partir del codigo enviado.
     */
    public String getDay(int daycode) {
        String dayOfWeek = "";
        for (TgeneCatalogDetail day : this.tdays) {
            if (day.getLegalcode().compareTo(String.valueOf(daycode)) == 0) {
                dayOfWeek = day.getDescription();
            }
        }
        return dayOfWeek;
    }

    public List<TgeneCatalogDetail> getTdays() {
        return this.tdays;
    }

    public void setTdays(List<TgeneCatalogDetail> tdays) {
        this.tdays = tdays;
    }

    /**
     * Entrega el valor de: initTime
     *
     * @return Date
     */
    public Date getInitTime() {
        java.util.Date dt = null;
        try {
            if (record != null && record.getInittime() != null) {
                dt = TIMEFORMAT.parse(this.record.getInittime());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dt;
    }

    /**
     * Fija el valor de: initTime
     *
     * @param initTime Valor a fijar en el atributo
     */
    public void setInitTime(Date initTime) {
        this.initTime = initTime;
        this.record.setInittime(TIMEFORMAT.format(initTime));
    }

    /**
     * Entrega el valor de: endTime
     *
     * @return Date
     */
    public Date getEndTime() {
        java.util.Date dt = null;
        try {
            if (record != null && record.getInittime() != null) {
                dt = TIMEFORMAT.parse(this.record.getFinishtime());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dt;
    }

    /**
     * Fija el valor de: endTime
     *
     * @param endTime Valor a fijar en el atributo
     */
    public void setEndTime(Date endTime) {
        this.endTime = endTime;
        this.record.setFinishtime(TIMEFORMAT.format(endTime));
    }

    public String getRecordDayDescription() {
        if (this.record != null) {
            for (TgeneCatalogDetail day : this.tdays) {
                if (day.getLegalcode().compareTo(this.record.getPk().getDay().toString()) == 0) {
                    return day.getDescription();
                }
            }
        }
        return null;
    }

}
