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

import java.util.ArrayList;

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.helper.MessageHelper;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pgeneral.safe.TsafeUserDetail;

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

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

    public UserChangePassAdmin() 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.querydatabase();
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void save() {
        try {
            if (!this.passwordvalidate()) {
                return;
            }
            TsafeUserDetail tsud = userdetail.getRecord();
            tsud.setPassword(callerhelper.getPasswordEncriptado(super.getMfilelds().get("p").toString()));
            tsud.setChangepassword("Y");
            userdetail.update();
            userdetail.save();
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Valida que el usuario ingrese la contrasena y la contrasena de validacion
     * y que las dos sean iguales.
     *
     * @return boolean
     * @throws Exception
     */
    private boolean passwordvalidate() throws Exception {
        Object p = super.getFieldvalue("p");
        Object np = super.getFieldvalue("np");
        if (p == null || np == null) {
            MessageHelper.setMessageError("msg_passwordrequired");
            return false;
        }
        if (!p.equals(np)) {
            MessageHelper.setMessageError("msg_passwordnomatch");
            return false;
        }
        return true;
    }

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

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

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

    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.querydatabase();
        this.addFilter("pk.usercode", this.userdetail.getRecord().getPk().getUsercode());
    }
}
