package com.fp.persistence.pgeneral.gene;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.fp.dto.hb.HibernateBean;

/**Clase que implementa la entidad de Hibernate que hace referencia a la tabla TGENEACCOUNTRELATIONSHIP*/
@Entity(name = "TgeneAccountRelationship")
@Table(name = "TGENEACCOUNTRELATIONSHIP")
public class TgeneAccountRelationship extends com.fp.dto.AbstractDataTransport implements Serializable, HibernateBean, Cloneable {

    /**
     * HashCode asociado con la Instancia
     */
    @Transient
    private int hashValue = 0;
    /**
     * Version de la Clase
     */
    private static final long serialVersionUID = 1L;
    /**
     * Clave primaria de la Entidad TgeneAccountRelationship
     */
    @EmbeddedId
    private TgeneAccountRelationshipKey pk;
    @Column(name = "MODULECODE", nullable = true)
    /**
     * Codigo de modulo
     */
    private String modulecode;
    @Column(name = "RELATIONSHIPCODE", nullable = true)
    /**
     * Codigo de relacion de la cuenta con el cliente
     */
    private String relationshipcode;
    @Column(name = "ISPRINCIPAL", nullable = true)
    /**
     * Indica si el codigo de relacion es principal, en este caso el codigo de cliente se asocia a la tabla tgeneaccount
     */
    private String isprincipal;
    @Column(name = "PRIORITY", nullable = true)
    /**
     * Prioridad del cliente en la cuenta.
     */
    private Integer priority;
    @Column(name = "CONDITION", nullable = true)
    /**
     * Condicion del cliente con la cuenta
     */
    private String condition;
    @Column(name = "PARTICIPATION", nullable = true)
    /**
     * Porcentaje de participacion del cliente con la solicitud.
     */
    private BigDecimal participation;
    @Column(name = "PERSONTYPE", nullable = true)
    /**
     * 1 Persona natural, 2 Persona Juridica.
     */
    private String persontype;

    /**Contructor por defecto*/
    public TgeneAccountRelationship() {
    }

    /**Contructor de TgeneAccountRelationship
    @param pPk Clave Primaria del entity
     */
    public TgeneAccountRelationship(TgeneAccountRelationshipKey pPk) {
        this();
        this.pk = pPk;
    }

    /**
     * Metodo que entrega datos de la tabla dada la clave primaria.
     * @param pEntityManager referencia de la session a obtener datos del bean.
     * @param pKey Caleve primaria del bean.
     * @return TgeneAccountRelationship
     */
    public static TgeneAccountRelationship find(EntityManager pEntityManager, TgeneAccountRelationshipKey pKey) throws Exception {
        TgeneAccountRelationship obj = pEntityManager.find(TgeneAccountRelationship.class, pKey);
        return obj;
    }

    /**Entrega la Clave primaria de TgeneAccountRelationship
    @return El objeto que referencia a la Clave primaria de TgeneAccountRelationship
     */
    public TgeneAccountRelationshipKey getPk() {
        return this.pk;
    }

    /**Fija un nuevo valor a la Clave primaria de TgeneAccountRelationship
    @param pPk El objeto que referencia a la nueva Clave primaria de TgeneAccountRelationship
     */
    public void setPk(TgeneAccountRelationshipKey pPk) {
        this.pk = pPk;
    }

    /**Obtiene el valor de modulecode
    @return valor de modulecode*/
    public String getModulecode() {
        return this.modulecode;
    }

    /**Fija el valor de modulecode
    @param pModulecode nuevo Valor de modulecode*/
    public void setModulecode(String pModulecode) {
        this.modulecode = pModulecode;
    }

    /**Obtiene el valor de relationshipcode
    @return valor de relationshipcode*/
    public String getRelationshipcode() {
        return this.relationshipcode;
    }

    /**Fija el valor de relationshipcode
    @param pRelationshipcode nuevo Valor de relationshipcode*/
    public void setRelationshipcode(String pRelationshipcode) {
        this.relationshipcode = pRelationshipcode;
    }

    /**Obtiene el valor de isprincipal
    @return valor de isprincipal*/
    public String getIsprincipal() {
        return this.isprincipal;
    }

    /**Fija el valor de isprincipal
    @param pIsprincipal nuevo Valor de isprincipal*/
    public void setIsprincipal(String pIsprincipal) {
        this.isprincipal = pIsprincipal;
    }

    /**Obtiene el valor de priority
    @return valor de priority*/
    public Integer getPriority() {
        return this.priority;
    }

    /**Fija el valor de priority
    @param pPriority nuevo Valor de priority*/
    public void setPriority(Integer pPriority) {
        this.priority = pPriority;
    }

    /**Obtiene el valor de condition
    @return valor de condition*/
    public String getCondition() {
        return this.condition;
    }

    /**Fija el valor de condition
    @param pCondition nuevo Valor de condition*/
    public void setCondition(String pCondition) {
        this.condition = pCondition;
    }

    /**Obtiene el valor de participation
    @return valor de participation*/
    public BigDecimal getParticipation() {
        return this.participation;
    }

    /**Fija el valor de participation
    @param pParticipation nuevo Valor de participation*/
    public void setParticipation(BigDecimal pParticipation) {
        this.participation = pParticipation;
    }

    /**Obtiene el valor de persontype
    @return valor de persontype*/
    public String getPersontype() {
        return this.persontype;
    }

    /**Fija el valor de persontype
    @param pPersontype nuevo Valor de persontype*/
    public void setPersontype(String pPersontype) {
        this.persontype = pPersontype;
    }

    @Override
    public boolean equals(Object rhs) {
        if (rhs == null) {
            return false;
        }
        if (!(rhs instanceof TgeneAccountRelationship)) {
            return false;
        }
        TgeneAccountRelationship that = (TgeneAccountRelationship) rhs;
        if ((this.getPk() == null) || (that.getPk() == null)) {
            return false;
        }
        return (this.getPk().equals(that.getPk()));
    }

    /**Implementaci锟絥 del metodo hashCode de la la entidad TgeneAccountRelationship
    @return el hashCode la instancia
     */
    @Override
    public int hashCode() {
        if (this.hashValue == 0) {
            int result = 17;
            if (this.getPk() == null) {
                result = super.hashCode();
            } else {
                result = this.getPk().hashCode();
            }
            this.hashValue = result;
        }
        return this.hashValue;
    }

    /**Implementaci锟絥 toString
     */
    @Override
    public String toString() {
        Field[] fs = this.getClass().getDeclaredFields();
        String data = "";
        for (Field f : fs) {
            try {
                String name = f.getName();
                if (f.getType().getName().compareTo("java.util.Set") == 0) {
                    continue;
                }
                if ((name.compareTo("hashValue") == 0) || (name.compareTo("serialVersionUID") == 0)) {
                    continue;
                }
                data += name + "=" + f.get(this) + ";";
            } catch (Exception e) {
                continue;
            }
        }
        if (data.compareTo("") == 0) {
            data = super.toString();
        }
        return data;
    }

    /**Implementaci锟絥 de la creaci锟絥 de un bean en blanco TgeneAccountRelationship
     */
    @Override
    public Object createInstance() {
        TgeneAccountRelationship instance = new TgeneAccountRelationship();
        instance.setPk(new TgeneAccountRelationshipKey());
        return instance;
    }

    /**Clona la entidad TgeneAccountRelationship
    @see com.fp.dto.hb.HibernateBean#cloneMe()
     */
    @Override
    public Object cloneMe() throws CloneNotSupportedException {
        TgeneAccountRelationship p = (TgeneAccountRelationship) this.clone();
        p.setPk((TgeneAccountRelationshipKey) this.pk.cloneMe());
        return p;
    }
    //METODOS MANUALES
    /** Sentencia que devuelve las productos de un cliente. */
    private static final String JPQL_ACC_RELATIONSHIP = "from TgeneAccountRelationship solrel  "
            + " where solrel.modulecode = :modulecode " + " and solrel.pk.personcode = :personcode ";
    /** Sentencia que devuelve las productos de un cliente dado el companycode. */
    private static final String JPQL_ACC_RELATIONSHIP_COMPANY = "from TgeneAccountRelationship solrel  "
            + " where solrel.modulecode = :modulecode " + " and solrel.pk.personcode = :personcode " + " and solrel.pk.company = :companycode ";

    /**
     * Entrega los cuentas de un cliente dado el m贸dulo
     * 
     * @param pModulecode Codigo del m胦dulo.
     * @param pPersoncode Codigo del cliente.
     * @return List<TgeneAccountRelationship>
     * @throws Exception
     */
    @SuppressWarnings(com.fp.common.helper.Constant.VUNCHECKED)
    public static List<TgeneAccountRelationship> findbyclient(EntityManager pEntityManager, String pModulecode, Integer pPersoncode) {
        List<TgeneAccountRelationship> lAccounts = null;
        Query qry = pEntityManager.createQuery(TgeneAccountRelationship.JPQL_ACC_RELATIONSHIP);
        qry.setParameter("modulecode", pModulecode);
        qry.setParameter("personcode", pPersoncode);
        lAccounts = qry.getResultList();
        return lAccounts;
    }

    /**
     * Entrega los cuentas de un cliente dado el m贸dulo
     * 
     * @param pModulecode Codigo del modulo.
     * @param pPersoncode Codigo del cliente.
     * @return List<TgeneAccountRelationship>
     * @throws Exception
     */
    @SuppressWarnings(com.fp.common.helper.Constant.VUNCHECKED)
    public static List<TgeneAccountRelationship> findbyCompany(EntityManager pEntityManager, String pModulecode, Integer pPersoncode, Integer pCompanycode) {
        List<TgeneAccountRelationship> lAccounts = null;
        Query qry = pEntityManager.createQuery(TgeneAccountRelationship.JPQL_ACC_RELATIONSHIP_COMPANY);
        qry.setParameter("modulecode", pModulecode);
        qry.setParameter("personcode", pPersoncode);
        qry.setParameter("companycode", pCompanycode);
        lAccounts = qry.getResultList();
        return lAccounts;
    }

    /** Sentencia que devuelve las productos de un cliente. */
    private static final String JPQL_ACC_CLIENTS = "from TgeneAccountRelationship accrel  "
            + " where accrel.pk.account = :account " + " and accrel.pk.company = :company ";
    /**
     * Entrega los clientes asociados a una cuenta
     * 
     * @param paccount Cuenta.
     * @param pcompany compania de la cuenta
     * @return List<TgeneAccountRelationship>
     * @throws Exception
     */
    @SuppressWarnings(com.fp.common.helper.Constant.VUNCHECKED)
    public static List<TgeneAccountRelationship> findbyAccount(EntityManager pEntityManager,String pAccount, Integer pCompany) {
        List<TgeneAccountRelationship> lAccounts = null;
        Query qry = pEntityManager.createQuery(TgeneAccountRelationship.JPQL_ACC_CLIENTS);
        qry.setParameter("account", pAccount);
        qry.setParameter("company", pCompany);
        lAccounts = qry.getResultList();
        return lAccounts;
    }

    /** Sentencia que devuelve las productos de un cliente. */
    private static final String JPQL_ACC_RELATIONSHIP_PRINCIPAL = " from TgeneAccountRelationship rel "
            + "where rel.modulecode = :strCrFacilityProduct and rel.pk.personcode = :pPersoncode "
            + "and rel.isprincipal = :clientype and rel.pk.company = :pcompany and rel.pk.account in "
            + "( select cfdet.pk.account from TcreditFacilityDetail cfdet where cfdet.pk.modulecode = :pModulecode "
            + "and cfdet.pk.productcode = :productcode and cfdet.pk.subproductcode = :subproductcode "
            + "and cfdet.pk.company = :pcompany and cfdet.pk.currencycode = :currencycode)";

    /**
     * Findbyclient.
     * 
     * @param pEntityManager the entity manager
     * @param pcompany the pcompany
     * @param pModulecode the modulecode
     * @param productcode the productcode
     * @param subproductcode the subproductcode
     * @param currencycode the currencycode
     * @param pPersoncode the personcode
     * @param pisprincipal the pisprincipal
     * @return the list
     */
    @SuppressWarnings(com.fp.common.helper.Constant.VUNCHECKED)
    public static List<TgeneAccountRelationship> findbyclient(EntityManager pEntityManager, Integer pcompany, String pModulecode, String productcode,
            String subproductcode, String currencycode, Integer pPersoncode, boolean pisprincipal) {
        List<TgeneAccountRelationship> lAccounts = null;

        String strCrFacilityProduct = "16";
        String strclienttype = !pisprincipal ? "N" : "Y";

        Query qry = pEntityManager.createQuery(TgeneAccountRelationship.JPQL_ACC_RELATIONSHIP_PRINCIPAL);
        qry.setParameter("pcompany", pcompany);
        qry.setParameter("pModulecode", pModulecode);
        qry.setParameter("productcode", productcode);
        qry.setParameter("subproductcode", subproductcode);
        qry.setParameter("currencycode", currencycode);
        qry.setParameter("pPersoncode", pPersoncode);
        qry.setParameter("strCrFacilityProduct", strCrFacilityProduct);
        qry.setParameter("clientype", strclienttype);

        lAccounts = qry.getResultList();
        return lAccounts;
    }
}
