package com.fp.frontend.controller.pcustomer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

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.pgeneral.gene.CatalogDetailController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pcustomer.company.TcustCompany;
import com.fp.persistence.pcustomer.gene.TcustPersonAddress;
import com.fp.persistence.pcustomer.gene.TcustPersonPhone;
import com.fp.persistence.pcustomer.gene.TcustPersonPhoneKey;
import com.fp.persistence.pgeneral.gene.TgeneCatalogDetail;

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

    private static final long serialVersionUID = 1L;

    public PersonPhoneController() throws Exception {
        super(TcustPersonPhone.class);
    }

    /**
     * Atributo para la lista de objetos TgeneCatalogDetail para tipo de
     * tel&eacute;fono
     */
    private List<TgeneCatalogDetail> lphonetype;

    /**
     * Atributo para el c&oacute;digo de persona
     */
    private Integer personcode;

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        this.lphonetype = CatalogDetailController.find("PHONETYPE");
    }

    /**
     * Incializa el controlador, cuando se esta utilizando una pagina que utliza
     * el controlador.
     */
    private void init() {
        try {
            this.recperpage = 10; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.record = new TcustPersonPhone();
            this.record.setPk(new TcustPersonPhoneKey());
            this.beanalias = "TCUSTPERSONPHONE";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Agrega el c&oacute;digo de persona para la consulta
     *
     * @param personcode c&oacute;digo de persona
     */
    public void addPersoncodeFilter(String personcode) {
        this.personcode = new Integer(personcode);
        super.addFilter("pk.personcode", personcode);
    }

    /**
     * M&eacute;todo para armar la consulta
     *
     * @return dto Objeto DtoQuery
     * @throws Exception
     */
    public DtoQuery getDtoQuery() throws Exception {
        super.addFilterDateto();
        DtoQuery dto = super.getDtoQuery(true);
        dto.setOrderby("t.pk.phonesequence"); // En en string van todos los campos de orden ("t.pk,  t.nombre, t.cpais").

        // subqueries
        SubQuery subquery = new SubQuery("TgeneCatalogDetail", "description", "phonetype",
                "i.pk.catalogcode = t.phonetypecatalogcode and i.pk.catalog = t.phonetypecatalog");
        dto.addSubQuery(subquery);
        return dto;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            DtoQuery dto = super.getDtoQuery(true);

            //Cargando el tipo de telefono
            SubQuery subQueryTipoTelefono = new SubQuery("TgeneCatalogDetail", "description",
                    "phonetype", "i.pk.catalog=t.phonetypecatalog and i.pk.catalogcode=t.phonetypecatalogcode");
            dto.addSubQuery(subQueryTipoTelefono);

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

            Request request = this.callerhelper.getRequest();
            request.setQueryTables(mtables);

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

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                lrecord = new ArrayList<TcustPersonPhone>();
                MessageHelper.setMessageError(resp);
            } else {
                lrecord = (List<TcustPersonPhone>) resp.get(beanalias);
                if (lrecord != null && !lrecord.isEmpty()) {
                    record = lrecord.get(0);
                }
                super.postQuery(lrecord);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Controla la respuesta de la consulta
     *
     * @param resp Objeto Response
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public void manageResponsePhones(Response resp) throws Exception {
        if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
            this.lrecord = new ArrayList<TcustPersonPhone>();
            MessageHelper.setMessageError(resp);
        } else {
            this.lrecord = (List<TcustPersonPhone>) resp.get(this.beanalias);
            super.postQuery(this.lrecord);
        }
    }

    @Override
    public void save() {
        try {
            Request request = this.callerhelper.getRequest();
            DtoSave dtosave = super.getDtoSave();
            if (!dtosave.pendingProcess()) {
                return;
            }
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();
            msave.put(this.beanalias, dtosave); // adicionar metadata de mantenimiento para cada tabla.

            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 update() {
        try {
//	    this.record.getPk().setPersoncode(((this.personcode==null) || this.personcode.equals(0))?null:this.personcode);
            if ((this.personcode == null) || (this.personcode == 0)) {
                //	this.record.getPk().setPhonesequence(this.getMaxNumber());
            }
            this.record.setPhonetypecatalogcode("PHONETYPE");
            for (TgeneCatalogDetail detail : this.lphonetype) {
                if (detail.getPk().getCatalog().equals(this.record.getPhonetypecatalog())) {
                    this.record.modifiedData.put("phonetype", detail.getDescription());
                }
            }
            super.update();
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

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

    /**
     * M&eacute;todo que obtiene el max de direcciones
     *
     * @return max N&uacute;mero max
     */
    private Integer getMaxNumber() {
        Integer max = 0;
        if (this.lrecord.size() > 0) {
            for (TcustPersonPhone phone : this.lrecord) {
                if (max.compareTo(phone.getPk().getPhonesequence()) < 0) {
                    max = phone.getPk().getPhonesequence();
                }
            }
        }
        return max + 1;
    }

    /**
     * Actualiza el registro
     */
    public void actualizar() {
        try {
            super.update();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static List<TcustPersonPhone> findAll(String codigopersona, String codigoTelFijo) {
        try {
            PersonPhoneController cc = new PersonPhoneController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk.personcode", codigopersona);
            cc.addFilter("phonetypecatalog", codigoTelFijo);
            cc.addFilterDateto();
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }
    public static TcustPersonPhone find(String codigopersona, String codigoTelFijo) {
        try {
            PersonPhoneController cc = new PersonPhoneController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk.personcode", codigopersona);
            cc.addFilter("phonetypecatalog", codigoTelFijo);
            cc.addFilterDateto();
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord.get(0);
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }
    
    
    /**
     * Obtiene todos los telefonos de una persona
     *
     * @param codigopersona
     * @return
     */
    public static List<TcustPersonPhone> findAllByPersonCode(String codigopersona) {
        try {
            PersonPhoneController cc = new PersonPhoneController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk.personcode", codigopersona);
            cc.addFilter("pk.dateto", "2999-12-31");
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    /**
     * Entrega una lista de objetos TgeneCatalogDetail tipo de tel&eacute;fono
     *
     * @return lphonetype Lista de objetos TgeneCatalogDetail tipo de
     * tel&eacute;fono
     */
    public List<TgeneCatalogDetail> getLphonetype() {
        return this.lphonetype;
    }

    /**
     * Fija una lista de objetos TgeneCatalogDetail tipo de tel&eacute;fono
     *
     * @param lphonetype Lista de objetos TgeneCatalogDetail tipo de
     * tel&eacute;fono
     */
    public void setLphonetype(List<TgeneCatalogDetail> lphonetype) {
        this.lphonetype = lphonetype;
    }

    /**
     * Entrega el c&oacute;digo de persona
     *
     * @return personcode C&oacute;digo de persona
     */
    public Integer getPersoncode() {
        return this.personcode;
    }

    /**
     * Fija el c&oacute;digo de persona
     *
     * @param personcode C&oacute;digo de persona
     */
    public void setPersoncode(Integer personcode) {
        this.personcode = personcode;
    }
}
