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

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.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.controller.pgeneral.gene.AreaController;
import com.fp.frontend.controller.pgeneral.gene.BranchController;
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.helper.MessageHelper;
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.TgeneChannels;
import com.fp.persistence.pgeneral.gene.TgeneLanguage;
import com.fp.persistence.pgeneral.gene.TgeneOffice;
import com.fp.persistence.pgeneral.safe.TsafeProfile;

/**
 * Clase controladora del bean TsafeUserDetail.
 *
 * @author Andres E. Carpio
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class UserPerfilAssiggnationController extends AbstractController<AbstractDataTransport> {

    private static final long serialVersionUID = 1L;
    List<TgeneChannels> lChannel;
    List<TgeneBranch> lBranch;
    List<TgeneOffice> lOffice;
    List<TgeneArea> lArea;
    List<TgeneLanguage> lLanguage;

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

    @ManagedProperty(value = "#{userProfileController}")
    private UserProfileController userProfile;

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

    @PostConstruct
    private void postconstruct() {
        this.init();
        this.lChannel = ChannelController.find();
        this.lBranch = BranchController.find(super.getLoginController().getRequest().getCompany()
                .toString());
        this.lArea = AreaController.find(super.getLoginController().getRequest().getCompany()
                .toString());
        this.lLanguage = LanguageController.find();

        // Inicializa autoconsulta
        super.startQuery();
    }

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

    public void loadOffice() {
        this.lOffice = OfficeController.find(
                this.userdetail.getRecord().getBranchcode().toString(), super.getLoginController()
                .getRequest().getCompany().toString());
    }

    @Override
    protected void querydatabase() {
        try {
            if (!this.userdetail.existAtLeastOneFilterValue()) {
                MessageHelper.setMessageError("msg_filterrequird");
                return;
            }
            this.userdetail.querydatabase();
            if (this.userdetail.getRecord().getPk().getUsercode() != null) {
                this.userProfile.getMfilters().put("pk.usercode", this.userdetail.getRecord().getPk().getUsercode());
                this.userProfile.querydatabase();
                this.loadOffice();
            }

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

    @Override
    public void save() {
        try {
            this.userdetail.update();

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

            DtoSave dtosave = this.userdetail.getDtoSave();
            if (dtosave.pendingProcess()) {
                dtosave.setIsForm(true);
                msave.put(this.userdetail.getBeanalias(), dtosave);
            }
            DtoSave dtosaveup = this.userProfile.getDtoSave();
            if (dtosaveup.pendingProcess()) {
                msave.put(this.userProfile.getBeanalias(), dtosaveup);
            }
            request.put("PANTALLA", "USUARIOSPERFIL_MOD1_TX120");
            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 {
        this.userdetail.postCommit(response);
        this.userProfile.postCommit(response);
    }

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

    /**
     * @return the userProfile
     */
    public UserProfileController getUserProfile() {
        return this.userProfile;
    }

    /**
     * @param userProfile the userProfile to set
     */
    public void setUserProfile(UserProfileController userProfile) {
        this.userProfile = userProfile;
    }

    public void onReturnPersonLov(SelectEvent event) throws Exception {
        TcustPersonDetail t = (TcustPersonDetail) event.getObject();
        this.userdetail.addFilter("pk.personcode", t.getPk().getPersoncode().toString());
        this.userdetail.addField("personname", t.getName());
        this.querydatabase();
    }

    public List<TgeneChannels> getlChannel() {
        return this.lChannel;
    }

    public void setlChannel(List<TgeneChannels> lChannel) {
        this.lChannel = lChannel;
    }

    public List<TgeneBranch> getlBranch() {
        return this.lBranch;
    }

    public void setlBranch(List<TgeneBranch> lBranch) {
        this.lBranch = lBranch;
    }

    public List<TgeneOffice> getlOffice() {
        return this.lOffice;
    }

    public void setlOffice(List<TgeneOffice> lOffice) {
        this.lOffice = lOffice;
    }

    public List<TgeneArea> getlArea() {
        return this.lArea;
    }

    public void setlArea(List<TgeneArea> lArea) {
        this.lArea = lArea;
    }

    public List<TgeneLanguage> getlLanguage() {
        return this.lLanguage;
    }

    public void setlLanguage(List<TgeneLanguage> lLanguage) {
        this.lLanguage = lLanguage;
    }

    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());
        this.userProfile.create();
        this.userProfile.getRecord().getPk().setUsercode(this.userdetail.getRecord().getPk().getUsercode());
        this.userProfile.getRecord().getPk().setProfilecode(t.getPk());
        this.userProfile.getRecord().put("profiledesc", t.getDescription());
        this.userProfile.update();

    }
}
