/**
 *
 */
package com.fp.frontend.controller.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.primefaces.context.RequestContext;

import com.fp.dto.AbstractDataTransport;
import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.query.SubQuery;
import com.fp.dto.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.controller.pcustomer.lov.PersonLovController;
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 amerchan
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class ChangeExpiredPassPersonalController extends AbstractController<TsafeUserDetail> implements Serializable {

    private static final long serialVersionUID = 1L;

    public ChangeExpiredPassPersonalController() throws Exception {
        super(TsafeUserDetail.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.create();
            this.lrecord = new ArrayList<>();
            this.beanalias = "TSAFEUSERDETAIL";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void querydatabase() {
        try {

            super.addFilter("pk.usercode", super.getLoginController().getRequest().getUser());
            super.addFilterDateto();
            super.addFilter("companycode", super.getLoginController().getRequest().getCompany().toString());

            if (!this.existAtLeastOneFilterValue()) {
                MessageHelper.setMessageError("msg_filterrequird");
                return;
            }

            Request request = this.callerhelper.getRequest();
            request.setTransactionModule("1");
            request.setTransactionCode(123);
            request.setTransactionVersion(1);

            DtoQuery dto = super.getDtoQuery(false);
            dto.setOrderby("t.pk.personcode"); // En en string van todos los campos de orden ("t.pk,  t.nombre, t.cpais").

            // subqueries
            SubQuery subquery = new SubQuery("TgeneChannels", "description", "chanelname", "i.pk = t.channelcode");
            dto.addSubQuery(subquery);

            SubQuery subquerya = new SubQuery("TgeneArea", "descripction", "areaname",
                    "i.pk.companycode = t.companycode and i.pk.areacode = t.areacode ");
            dto.addSubQuery(subquerya);

            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(this.beanalias, dto); // permite adicionar mas de una tabla.

            request.setQueryTables(mtables);

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

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.record = new TsafeUserDetail();
                MessageHelper.setMessageError(resp);
            } else {
                this.record = (TsafeUserDetail) resp.get(this.beanalias);
                if (this.record != null) {
                    //                    this.userprofile.addFilter("pk.usercode", this.record.getPk().getUsercode());
                    //                    this.userprofile.query();
                    TcustPersonDetail tcpd = PersonLovController.find(this.record.getPk().getPersoncode().toString());
                    super.addField("personname", tcpd != null ? tcpd.getName() : "");
                    super.postQuery((AbstractDataTransport) resp.get(this.beanalias));
                } else {
                    //                    this.userprofile.setLrecord(null);
                    this.create();
                }
            }

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

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

            String oldPass = this.callerhelper.getPasswordEncriptado((String) this.getMfilelds().get("oldpassword"));
            String newPass = this.callerhelper.getPasswordEncriptado((String) this.getMfilelds().get("newpassword"));

            this.record.put("newpassword", this.getMfilelds().get("newpassword"));
            this.record.put("origination", newPass);
            this.record.put("oldpassword", oldPass);

            this.record.setPassword(newPass);
            if (this.record.getChangepassword().compareTo("Y") == 0) {
                this.record.setChangepassword("N");
            }
            this.update();

            Request request = this.callerhelper.getRequest();
            request.setTransactionModule("1");
            request.setTransactionCode(123);
            request.setTransactionVersion(1);

            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();
            DtoSave dtoSavePassword = super.getDtoSave();
            dtoSavePassword.setIsForm(true);
            if (!dtoSavePassword.pendingProcess()) {
                return;
            }
            msave.put(this.beanalias, dtoSavePassword);
            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);
        }
    }

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

    @Override
    public void postCommit(Response response) throws Exception {
        super.postCommitGeneric(response, this.beanalias);
        RequestContext.getCurrentInstance().execute("dialogChangePassword.hide()");
    }

    /**
     * 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("newpassword");
        Object np = super.getFieldvalue("confirmpassword");
        if ((p == null) || (np == null)) {
            MessageHelper.setMessageError("msg_passwordrequired");
            return false;
        }
        if (!p.equals(np)) {
            MessageHelper.setMessageError("msg_passwordnomatch");
            return false;
        }
        return true;
    }

}
