package com.fp.frontend.controller.bpm;

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.ManagedProperty;
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.bpm.lov.GroupsLovController;
import com.fp.frontend.controller.pcustomer.lov.PersonLovController;
import com.fp.frontend.controller.pgeneral.safe.UserDetailController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pbpm.gene.TbpmGroups;
import com.fp.persistence.pbpm.gene.TbpmGroupsUsers;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.sun.mail.handlers.message_rfc822;

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

    private static final long serialVersionUID = 1L;

    public GroupsUsersController() throws Exception {
        super(TbpmGroupsUsers.class);
    }

    @ManagedProperty(value = "#{userDetailController}")
    private UserDetailController userdetail;

    @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 = 15; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "GROUPSUSERS";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Crea una instancia de TgeneTransactionProcess y marca el registro como
     * nuevo.
     *
     * @throws Exception
     */
    @Override
    public void create() throws Exception {
        if (super.getMfilters().get("pk.groupcode") == null) {
            MessageHelper.setMessageError("msg_grouprequird");
            return;
        }
        super.create();
        this.record.getPk().setCompanycode(super.getLoginController().getRequest().getCompany());
        this.record.getPk().setGroupcode(super.getMfilters().get("pk.groupcode"));
    }

    @Override
    public void update() throws Exception {
        if (record.getPk().getUsercode() == null) {
            MessageHelper.setMessageError("msg_userrequired");
        } else {
            super.update();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {

            super.addFilter("pk.companycode", super.getLoginController().getRequest().getCompany().toString());

            if (super.getMfilters().get("pk.groupcode") == null) {
                MessageHelper.setMessageError("msg_grouprequird");
                return;
            }

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

            //Subquery
            SubQuery subquery2 = new SubQuery("TcustPersonDetail", "name", "username",
                    "i.pk.dateto = to_date('2999-12-31', 'yyyy-MM-dd') and "
                    + "i.pk.personcode = (select a.personcode from TsafeUser a where a.pk = t.pk.usercode and a.companycode=t.pk.companycode)");
            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<TbpmGroupsUsers>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TbpmGroupsUsers>) resp.get(this.beanalias);
                super.postQuery(this.lrecord);
            }

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

    @Override
    public void save() {
        try {

            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();
            Request request = this.callerhelper.getRequest();

            DtoSave dtosave = super.getDtoSave();
            dtosave.setReturnpk(true); // Para que el core devuelva el pk de los registros nuevos.

            if (!dtosave.pendingProcess()) {
                return;
            }

            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 openGroupsLov() {
        Map<String, List<String>> params = new HashMap<>();
        GroupsLovController.openLov(params);
    }

    public void onReturnGroupsLov(SelectEvent event) throws Exception {
        TbpmGroups t = (TbpmGroups) event.getObject();
        super.addFilter("pk.groupcode", t.getPk().getGroupcode());
        super.addField("description", t.getDescription());
        this.query();
    }

    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();
        this.userdetail.getMfilters().clear();
        this.userdetail.addFilter("pk.personcode", t.getPk().getPersoncode().toString());
        this.userdetail.query();
        if (this.userdetail.getRecord() == null) {
            this.record.getPk().setUsercode(null);
            this.record.getModifiedData().put("username", null);
            MessageHelper.setMessageError("msg_userNotFound");
            return;
        }
        if (this.userdetail.getRecord().getIsuserbpm() == null || this.userdetail.getRecord().getIsuserbpm().equals("N")) {
            this.record.getPk().setUsercode(null);
            this.record.getModifiedData().put("username", null);
            MessageHelper.setMessageError("msg_notUserBpm");
            return;
        }
        this.record.getPk().setUsercode(this.userdetail.getRecord().getPk().getUsercode());
        this.record.getModifiedData().put("username", t.getName());
    }

    /**
     * Entrega el valor de: userdetail
     *
     * @return UserDetailController
     */
    public UserDetailController getUserdetail() {
        return this.userdetail;
    }

    /**
     * Fija el valor de: userdetail
     *
     * @param userdetail Valor a fijar en el atributo.
     */
    public void setUserdetail(UserDetailController userdetail) {
        this.userdetail = userdetail;
    }
}
