/*
 * 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 org.primefaces.event.SelectEvent;

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

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

    private static final long serialVersionUID = 1L;
    @ManagedProperty(value = "#{userDetailController}")
    private UserDetailController userdetail;
    @ManagedProperty(value = "#{userProfileController}")
    private UserProfileController userprofile;

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

    @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.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();
            this.getMfilelds().put("personname", this.userdetail.getMfilelds().get("personname"));
            if (this.userdetail.getRecord().getPk().getUsercode() != null) {
                this.userprofile.addFilter("pk.usercode", this.userdetail.getRecord().getPk().getUsercode());
                this.userprofile.query();
            } else {
                this.userprofile.setLrecord(null);
                MessageHelper.setMessageError("msg_userNotFound");
            }

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

    @Override
    public void save() {
        try {
            if (this.validateUser()) {
                MessageHelper.setMessageError("msg_userrequired");
                return;
            }
            if (this.userdetail.getRecord().getUserstatuscatalog().equals("ENT")) {
                MessageHelper.setMessageError("msg_pendingActivation");
                return;
            }
            if (this.userdetail.getRecord().getPassword() == null) {
                String passwd = this.callerhelper.getPasswordEncriptado(this.userdetail.getRecord().getPk().getUsercode());
                this.userdetail.getRecord().setPassword(passwd);
            }

            this.userdetail.getRecord().setUserstatuscatalog("ACT");
            this.userdetail.update();
            this.userdetail.save();
            userdetail.getRecord().getModifiedData().put("statusdesc", "ACTIVO");
        } 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);
    }

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

    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) {
            this.addFilter("pk.usercode", this.userdetail.getRecord().getPk().getUsercode());
            this.userprofile.addFilter("pk.usercode", this.userdetail.getRecord().getPk().getUsercode());
            this.userprofile.query();
        } else {
            MessageHelper.setMessageError("msg_userNotFound");
        }
    }
}
