/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fp.frontend.controller.security;

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 javax.faces.context.FacesContext;

import org.primefaces.event.SelectEvent;

import com.fp.dto.AbstractDataTransport;
import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.controller.armas.parametros.CentroControlArmasController;
import com.fp.frontend.controller.armas.parametros.TarmCentroControlJurController;
import com.fp.frontend.controller.pcustomer.lov.PersonLovController;
import com.fp.frontend.controller.pgeneral.gene.AreaController;
import com.fp.frontend.controller.pgeneral.gene.BranchController;
import com.fp.frontend.controller.pgeneral.gene.CatalogDetailController;
import com.fp.frontend.controller.pgeneral.gene.ChannelController;
import com.fp.frontend.controller.pgeneral.gene.LanguageController;
import com.fp.frontend.controller.pgeneral.gene.OfficeController;
import com.fp.frontend.controller.pgeneral.lov.ProfileLovController;
import com.fp.frontend.controller.pgeneral.safe.TerminalController;
import com.fp.frontend.controller.pgeneral.safe.UserDetailController;
import com.fp.frontend.controller.pgeneral.safe.UserProfileController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.frontend.utility.MsgControlArmas;
import com.fp.persistence.parmas.param.TarmCentroControl;
import com.fp.persistence.parmas.param.TarmCentroControlJur;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pgeneral.gene.TgeneArea;
import com.fp.persistence.pgeneral.gene.TgeneBranch;
import com.fp.persistence.pgeneral.gene.TgeneCatalogDetail;
import com.fp.persistence.pgeneral.gene.TgeneChannels;
import com.fp.persistence.pgeneral.gene.TgeneLanguage;
import com.fp.persistence.pgeneral.gene.TgeneOffice;
import com.fp.persistence.pgeneral.safe.TsafeProfile;
import com.fp.persistence.pgeneral.safe.TsafeTerminal;
import com.fp.persistence.pgeneral.safe.TsafeUserDetail;
import com.fp.persistence.pgeneral.safe.TsafeUserProfile;

/**
 * Clase controladora de modifyuser
 *
 * @author BPTWPA
 * @version 2.1
 */
@SuppressWarnings("serial")
@ManagedBean
@ViewScoped
public class ModifyUserController extends AbstractController<AbstractDataTransport> {

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

    public ModifyUserController() throws Exception {
        super(AbstractDataTransport.class);
    }
    /**
     * Atributo para la lista de objetos TgeneCatalogDetail para el Status del
     * usuario
     */
    private List<TgeneCatalogDetail> luserStatus;
    /**
     * Atributo para la lista de objetos TsafeTerminal para el terminal
     */
    private List<TsafeTerminal> lterminal;
    /**
     * Atributo para la lista de idiomas
     */
    private List<TgeneLanguage> llanguage;
    /**
     * Atributo para los canales
     */
    private List<TgeneChannels> lchannel;
    /**
     * Atributo para la llist de sucursales
     */
    private List<TgeneBranch> lbranch;
    /**
     * Atributo para las oficinas
     */
    private List<TgeneOffice> loffice;
    /**
     * Atributo para las areas
     */
    private List<TgeneArea> larea;

    private String centroControl;

    private String unidad;

    private List<TgeneCatalogDetail> centroControls;
    /**
     * Atributo para la lista de objetos TgeneCatalogDetail
     */
    private List<TarmCentroControl> unidades;
    /**
     * Deshabilita la pantalla despu&eacute;s de grabar la solicitud
     */
    private boolean deshabilitarPantalla;

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        //list
        this.luserStatus = CatalogDetailController.find("USERSTATUS");
        this.lterminal = TerminalController.find(super.getLoginController().getRequest().getCompany().toString());
        this.llanguage = LanguageController.find();
        this.lchannel = ChannelController.find();
        this.lbranch = BranchController.find(super.getLoginController().getRequest().getCompany().toString());
        this.larea = AreaController.find(super.getLoginController().getRequest().getCompany().toString());
        this.unidades = new ArrayList<>();
        this.unidad = "";
        this.centroControls = CatalogDetailController.find("INSTITUCION");
        this.deshabilitarPantalla = Boolean.TRUE;

    }

    /**
     * Incializa el controlador, cuando se esta utilizando una pagina que utliza
     * el controlador.
     */
    private void init() {
        try {
            this.lrecord = new ArrayList<>();
            this.beanalias = "CHANGEPASSADMIN";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    protected void querydatabase() {
        try {
            if (!this.existAtLeastOneFilterValue()) {
                MessageHelper.setMessageError("msg_filterrequird");
                return;
            }
            this.userdetail.getMfilters().clear();
            this.userdetail.getMfilelds().clear();
            this.userdetail.getMfilters().put("pk.usercode", this.getMfilters().get("pk.usercode"));
            this.userdetail.query();

            if (this.userdetail.getRecord().getPk().getUsercode() != null) {
                this.deshabilitarPantalla = Boolean.FALSE;
                loadCentroControlUnidad();
                this.loffice = OfficeController.find(this.userdetail.getRecord().getBranchcode().toString(), super.getLoginController().getRequest().getCompany().toString());
                this.userprofile.addFilter("pk.usercode", this.userdetail.getRecord().getPk().getUsercode());
                this.userprofile.query();
            } else {
                this.deshabilitarPantalla = Boolean.TRUE;
                this.userdetail.create();
                this.userdetail.getRecord().setUserstatuscatalogcode("USERSTATUS");
                this.userdetail.getRecord().setUserstatuscatalog(null);
                this.userprofile.setLrecord(null);
                MessageHelper.setMessageError("msg_userNotFound");
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Carga el centro de control por el tarm centro de control de armas
     */
    private void loadCentroControlUnidad() {
        //Consultar el centro de control de armas
        if (userdetail.getRecord().getCcentrocontrol() != null && !userdetail.getRecord().getCcentrocontrol().isEmpty()) {
            TarmCentroControl tarmCentroControl = CentroControlArmasController.findPorCodigo(userdetail.getRecord().getCcentrocontrol());
            if (tarmCentroControl != null) {
                centroControl = tarmCentroControl.getInstitucion();
                unidad = tarmCentroControl.getNombreinstitucion();
                seleccionaCentroControl();
            } else {
                centroControl = "";
                unidad = "";
            }
        } else {
            centroControl = "";
            unidad = "";
        }
    }

    @Override
    public void save() {
        try {
            if (this.validateUser()) {
                MessageHelper.setMessageError("msg_userrequired");
                return;
            }

            Request request = this.callerhelper.getRequest();
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();
            //Obteniendo los datos del usuario logueado
            TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("TSAFEUSERDETAIL");
            this.userdetail.getRecord().setModifyuser(tsafeUserDetail.getPk().getUsercode());
            //Consultar el centro de control de armas
            TarmCentroControl tarmCentroControl = CentroControlArmasController.findxCcontrolUnidad(centroControl, unidad);

            if (tarmCentroControl != null && tarmCentroControl.getInstitucion().equals(centroControl)) {
                this.userdetail.getRecord().setCcentrocontrol(tarmCentroControl.getPk());
            } else {
                centroControl = "";
            }

            this.userdetail.update();

            DtoSave dtosaveuserdet = this.userdetail.getDtoSave();
            if (dtosaveuserdet.pendingProcess()) {
                dtosaveuserdet.setIsForm(true);
                msave.put(this.userdetail.getBeanalias(), dtosaveuserdet);
            }

            DtoSave dtosaveuserprofile = this.userprofile.getDtoSave();
            if (dtosaveuserprofile.pendingProcess()) {
                msave.put(this.userprofile.getBeanalias(), dtosaveuserprofile);
            }

            //            this.userdetail.save();
            //            this.userprofile.save();
            request.setSaveTables(msave);
            Response resp = this.callerhelper.executeSave(request);
            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) == 0) {
                this.postCommit(resp);
                this.userdetail.postCommit(resp);
                this.userprofile.postCommit(resp);
                MessageHelper.setMessageInfo(resp);
            } else {
                MessageHelper.setMessageError(resp);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    private boolean validateUser() {
        boolean result = false;
        if (this.userdetail.getRecord().getPk() == null) {
            result = true;
        }
        return result;
    }

    @Override
    public void postCommit(Response response) throws Exception {
        super.postCommitGeneric(response, this.beanalias);
    }

    /**
     * Carga las oficinas
     */
    public void loadOffice() {
        this.loffice = OfficeController.find(this.userdetail.getRecord().getBranchcode().toString(), super.getLoginController().getRequest().getCompany().toString());
    }

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

    /**
     * Entrega el valor de: userprofile
     *
     * @return UserProfileController
     */
    public UserProfileController getUserprofile() {
        return this.userprofile;
    }

    /**
     * Fija el valor de: userprofile
     *
     * @param UserProfileController
     */
    public void setUserprofile(UserProfileController userprofile) {
        this.userprofile = userprofile;
    }

    /**
     * Carga las unidades de control por el centro de control
     */
    public void seleccionaCentroControl() {
        if (centroControl != null) {
            unidades = CentroControlArmasController.findxInstitucion(centroControl);
        } else {
            unidades = new ArrayList<>();
            userdetail.getRecord().setCcentrocontrol(null);
        }
    }

    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.getMfilelds().clear();
        this.userdetail.addFilter("pk.personcode", t.getPk().getPersoncode().toString());
        this.userdetail.addField("personname", t.getName());
        this.userdetail.query();

        if (this.userdetail.getRecord().getPk().getUsercode() != null) {
            deshabilitarPantalla = Boolean.FALSE;
            loadCentroControlUnidad();
            this.loffice = OfficeController.find(this.userdetail.getRecord().getBranchcode().toString(), super.getLoginController().getRequest().getCompany().toString());
            this.addFilter("pk.usercode", this.userdetail.getRecord().getPk().getUsercode());
            this.userprofile.addFilter("pk.usercode", this.userdetail.getRecord().getPk().getUsercode());
            this.userprofile.query();
        } else {
            deshabilitarPantalla = Boolean.TRUE;
            this.userdetail.getRecord().setUserstatuscatalog(null);
            MessageHelper.setMessageError("msg_userNotFound");
        }
    }

    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();
        this.userprofile.create();
        if (this.userdetail.getRecord().getPk() != null) {
            this.userprofile.getRecord().getPk().setUsercode(this.userdetail.getRecord().getPk().getUsercode());
            this.userprofile.getRecord().getPk().setProfilecode(t.getPk());
            this.userprofile.getRecord().put("profiledesc", t.getDescription());
            if (this.verifyProfile()) {
                MessageHelper.setMessageError("msg_userExist");
            } else {
                this.userprofile.update();
            }
        } else {
            MessageHelper.setMessageError("msg_userrequired");
        }
    }

    /**
     * Verifica si hay un perfil seleccionado
     *
     * @return result V/F
     */
    private boolean verifyProfile() {
        boolean result = false;
        if (!this.userprofile.getLrecord().isEmpty()) {
            for (TsafeUserProfile profile : this.userprofile.getLrecord()) {
                if (profile.getPk().getProfilecode().compareTo(this.userprofile.getRecord().getPk().getProfilecode()) == 0) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

    /**
     * Entrega una lista de objetos TgeneCatalogDetail
     *
     * @return luserStatus Lista de objetos TgeneCatalogDetail
     */
    public List<TgeneCatalogDetail> getLuserStatus() {
        return this.luserStatus;
    }

    /**
     * Fija una lista de objetos TgeneCatalogDetail
     *
     * @param luserStatus Lista de objetos TgeneCatalogDetail
     */
    public void setLuserStatus(List<TgeneCatalogDetail> luserStatus) {
        this.luserStatus = luserStatus;
    }

    /**
     * Entrega una lista de objetos TsafeTerminal
     *
     * @return lterminal Lista de objetos TsafeTerminal
     */
    public List<TsafeTerminal> getLterminal() {
        return this.lterminal;
    }

    /**
     * Fija una lista de objetos TsafeTerminal
     *
     * @param lterminal Lista de objetos TsafeTerminal
     */
    public void setLterminal(List<TsafeTerminal> lterminal) {
        this.lterminal = lterminal;
    }

    /**
     * Entrega una lista de objetos TgeneLanguage
     *
     * @return lterminal Lista de objetos TgeneLanguage
     */
    public List<TgeneLanguage> getLlanguage() {
        return this.llanguage;
    }

    /**
     * Fija una lista de objetos TgeneLanguage
     *
     * @param lterminal Lista de objetos TgeneLanguage
     */
    public void setLlanguage(List<TgeneLanguage> llanguage) {
        this.llanguage = llanguage;
    }

    /**
     * Entrega una lista de objetos TgeneChannels
     *
     * @param lchannel Lista de objetos TgeneLanguage
     */
    public List<TgeneChannels> getLchannel() {
        return this.lchannel;
    }

    /**
     * Fija una lista de objetos TgeneChannels
     *
     * @param lchannel Lista de objetos TgeneChannels
     */
    public void setLchannel(List<TgeneChannels> lchannel) {
        this.lchannel = lchannel;
    }

    /**
     * Entrega una lista de objetos TgeneBranch
     *
     * @return lbranch Lista de objetos TgeneLanguage
     */
    public List<TgeneBranch> getLbranch() {
        return this.lbranch;
    }

    /**
     * Fija una lista de objetos TgeneBranch
     *
     * @param lbranch Lista de objetos TgeneLanguage
     */
    public void setLbranch(List<TgeneBranch> lbranch) {
        this.lbranch = lbranch;
    }

    /**
     * Entrega una lista de objetos TgeneOffice
     *
     * @return loffice Lista de objetos TgeneOffice
     */
    public List<TgeneOffice> getLoffice() {
        return this.loffice;
    }

    /**
     * Fija una lista de objetos TgeneOffice
     *
     * @param loffice Lista de objetos TgeneOffice
     */
    public void setLoffice(List<TgeneOffice> loffice) {
        this.loffice = loffice;
    }

    /**
     * Entrega una lista de objetos TgeneArea
     *
     * @return larea Lista de objetos TgeneArea
     */
    public List<TgeneArea> getLarea() {
        return this.larea;
    }

    /**
     * Fija una lista de objetos TgeneArea
     *
     * @param larea Lista de objetos TgeneArea
     */
    public void setLarea(List<TgeneArea> larea) {
        this.larea = larea;
    }

    public List<TgeneCatalogDetail> getCentroControls() {
        return centroControls;
    }

    public void setCentroControls(List<TgeneCatalogDetail> centroControls) {
        this.centroControls = centroControls;
    }

    public List<TarmCentroControl> getUnidades() {
        return unidades;
    }

    public void setUnidades(List<TarmCentroControl> unidades) {
        this.unidades = unidades;
    }

    public String getCentroControl() {
        return centroControl;
    }

    public void setCentroControl(String centroControl) {
        this.centroControl = centroControl;
    }

    public boolean isDeshabilitarPantalla() {
        return deshabilitarPantalla;
    }

    public void setDeshabilitarPantalla(boolean deshabilitarPantalla) {
        this.deshabilitarPantalla = deshabilitarPantalla;
    }

    public String getUnidad() {
        return unidad;
    }

    public void setUnidad(String unidad) {
        this.unidad = unidad;
    }

}
