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.AbstractDataTransport;
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.pcustomer.lov.PersonLovController;
import com.fp.frontend.controller.pgeneral.safe.UserDetailController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;

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

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

    public AssignmentsController() throws Exception {
        super(AbstractDataTransport.class);
    }

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

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

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

    @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.recordmap = new HashMap<String, Object>();
            this.recperpage = 10; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "tasks";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

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

            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("userCri", super.getMfilters().get("user"));
            request.put("cri", "");
            request.put("queryalias", "ASIGNEDTASKS");

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

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

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

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

    /**
     * M&eacute;todo que llama al lov de Personas
     */
    public void openPersonLov() {
        Map<String, List<String>> params = new HashMap<>();
        PersonLovController.openLov(params);
    }

    /**
     * Maneja la respuesta del Lov de Personas
     *
     * @param event
     * @throws Exception
     */
    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) {
            MessageHelper.setMessageError("msg_userNotFound");
            return;
        }
        if (this.userdetail.getRecord().getIsuserbpm() == null || this.userdetail.getRecord().getIsuserbpm().equals("N")) {
            MessageHelper.setMessageError("msg_notUserBpm");
            return;
        }
        this.recordmap.put("userasigned", this.userdetail.getRecord().getPk().getUsercode());
        this.recordmap.put("nameasigned", t.getName());
    }

    /**
     * Ejecuta el action del asigned
     */
    public void assigned() {
        try {
            Request request = this.callerhelper.getRequest();
            request.setUser((String) this.recordmap.get("userasigned"));
            request.put("TID", this.recordmap.get("tid"));

            Response resp = this.callerhelper.executeSave(request);
            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) == 0) {
                this.postCommit(resp);
                MessageHelper.setMessageInfo(resp);
                this.querydatabase();
            } else {
                MessageHelper.setMessageError(resp);
            }

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

    /**
     * Entrega una lista de mapas
     *
     * @return ltasks Lista de mapas
     */
    public List<Map<String, Object>> getLtasks() {
        return ltasks;
    }

    /**
     * Fija una lista de mapas
     *
     * @param ltasks Lista de mapas
     */
    public void setLtasks(List<Map<String, Object>> ltasks) {
        this.ltasks = ltasks;
    }

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

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

    /**
     * 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;
    }
}
