package com.fp.persistence.pgeneral.product.rate;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Date;
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 javax.persistence.Version;

import com.fp.dto.hb.Cache;
import com.fp.dto.hb.HibernateBean;
import com.fp.dto.hb.Log;
import javax.persistence.GeneratedValue;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

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

    /**
     * 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 TgeneBaseRateDetail
     */
    @EmbeddedId
    @GenericGenerator(name = "seq_id", strategy = "com.fp.general.keygen.SubSequenceKey", parameters = {
        @Parameter(name = "sql", value = "select coalesce(max(RATESEQUENCE),0)+1 from TGENEBASERATEDETAIL where BASERATECATALOG=:baseratecatalog and BASERATECATALOGCODE=:baseratecatalogcode and CURRENCYCODE=:currencycode"),
        @Parameter(name = "type", value = "java.lang.Integer"),
        @Parameter(name = "param", value = "baseratecatalog,pk.baseratecatalog;baseratecatalogcode,pk.baseratecatalogcode;currencycode,pk.currencycode"),
        @Parameter(name = "field", value = "ratesequence")})
    @GeneratedValue(generator = "seq_id")
    private TgeneBaseRateDetailKey pk;
    @Version
    @Column(name = "RECORDVERSION", nullable = true)
    /**
     * Manejo de optimistic locking
     */
    private Integer recordversion;
    @Column(name = "RATE", nullable = true)
    /**
     * Tasa asociada
     */
    private BigDecimal rate;
    @Column(name = "NOMINALRATE", nullable = false)
    /**
     * Y, Indica que el tipo de tasa referencial es nominal, N el tipo de tasa
     * es efectiva.
     */
    private String nominalrate;
    @Column(name = "VALIDITYRATE", nullable = false)
    /**
     * Fecha desde la cual esta vigente la defincion de la tasa base.
     */
    private Date validityrate;
    @Column(name = "EXPIRATIONDATE", nullable = false)
    /**
     * Fecha hasta la cual esta vigente la definicion de la tasa base.
     */
    private Date expirationdate;

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

    /**
     * Contructor de TgeneBaseRateDetail
     *
     * @param pPk Clave Primaria del entity
     * @param pNominalrate Y, Indica que el tipo de tasa referencial es nominal,
     * N el tipo de tasa es efectiva.
     * @param pValidityrate Fecha desde la cual esta vigente la defincion de la
     * tasa base.
     * @param pExpirationdate Fecha hasta la cual esta vigente la definicion de
     * la tasa base.
     */
    public TgeneBaseRateDetail(TgeneBaseRateDetailKey pPk, String pNominalrate, Date pValidityrate, Date pExpirationdate) {
        this();
        this.pk = pPk;
        this.nominalrate = pNominalrate;
        this.validityrate = pValidityrate;
        this.expirationdate = pExpirationdate;
    }

    /**
     * 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 TgeneBaseRateDetail
     */
    public static TgeneBaseRateDetail find(EntityManager pEntityManager, TgeneBaseRateDetailKey pKey) throws Exception {
        TgeneBaseRateDetail obj = pEntityManager.find(TgeneBaseRateDetail.class, pKey);
        return obj;
    }

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

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

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

    /**
     * Fija el valor de recordversion
     *
     * @param pRecordversion nuevo Valor de recordversion
     */
    public void setRecordversion(Integer pRecordversion) {
        this.recordversion = pRecordversion;
    }

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

    /**
     * Fija el valor de rate
     *
     * @param pRate nuevo Valor de rate
     */
    public void setRate(BigDecimal pRate) {
        this.rate = pRate;
    }

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

    /**
     * Fija el valor de nominalrate
     *
     * @param pNominalrate nuevo Valor de nominalrate
     */
    public void setNominalrate(String pNominalrate) {
        this.nominalrate = pNominalrate;
    }

    /**
     * Obtiene el valor de validityrate
     *
     * @return valor de validityrate
     */
    public Date getValidityrate() {
        return this.validityrate;
    }

    /**
     * Fija el valor de validityrate
     *
     * @param pValidityrate nuevo Valor de validityrate
     */
    public void setValidityrate(Date pValidityrate) {
        this.validityrate = pValidityrate;
    }

    /**
     * Obtiene el valor de expirationdate
     *
     * @return valor de expirationdate
     */
    public Date getExpirationdate() {
        return this.expirationdate;
    }

    /**
     * Fija el valor de expirationdate
     *
     * @param pExpirationdate nuevo Valor de expirationdate
     */
    public void setExpirationdate(Date pExpirationdate) {
        this.expirationdate = pExpirationdate;
    }

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

    /**
     * Implementacion del metodo hashCode de la la entidad TgeneBaseRateDetail
     *
     * @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;
    }

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

    /**
     * Implementacion de la creacion de un bean en blanco TgeneBaseRateDetail
     */
    @Override
    public Object createInstance() {
        TgeneBaseRateDetail instance = new TgeneBaseRateDetail();
        instance.setPk(new TgeneBaseRateDetailKey());
        return instance;
    }

    /**
     * Clona la entidad TgeneBaseRateDetail
     *
     * @see com.fp.dto.hb.HibernateBean#cloneMe()
     */
    @Override
    public Object cloneMe() throws CloneNotSupportedException {
        TgeneBaseRateDetail p = (TgeneBaseRateDetail) this.clone();
        p.setPk((TgeneBaseRateDetailKey) this.pk.cloneMe());
        return p;
    }

    // METODOS MANUALES
    public boolean equalsWithoutRateSequence(Object rhs) {
        if (rhs == null) {
            return false;
        }
        if (!(rhs instanceof TgeneBaseRateDetail)) {
            return false;
        }
        TgeneBaseRateDetail that = (TgeneBaseRateDetail) rhs;
        if ((this.getPk() == null) || (that.getPk() == null)) {
            return false;
        }
        // Validacion de claves primarias
        TgeneBaseRateDetailKey thatpk = that.getPk();
        TgeneBaseRateDetailKey thispk = this.getPk();

        if (thatpk == null) {
            return false;
        }
        if (!(thatpk instanceof TgeneBaseRateDetailKey)) {
            return false;
        }
        if ((thispk.getBaseratecatalog() == null) || (thatpk.getBaseratecatalog() == null)) {
            return false;
        }
        if (!thispk.getBaseratecatalog().equals(thatpk.getBaseratecatalog())) {
            return false;
        }
        if ((thispk.getBaseratecatalogcode() == null) || (thatpk.getBaseratecatalogcode() == null)) {
            return false;
        }
        if (!thispk.getBaseratecatalogcode().equals(thatpk.getBaseratecatalogcode())) {
            return false;
        }
        if ((thispk.getCurrencycode() == null) || (thatpk.getCurrencycode() == null)) {
            return false;
        }
        if (!thispk.getCurrencycode().equals(thatpk.getCurrencycode())) {
            return false;
        }

        return true;
    }
    private static final String JPQL_RATEDETAIL = " from TgeneBaseRateDetail tdet " + " where tdet.pk.currencycode = :currencycode "
            + " and tdet.pk.baseratecatalog = :baseratecatalog" + " and tdet.pk.baseratecatalogcode = :baseratecatalogcode";

    /**
     * Metodo que entrega una lista de datos requeridos de clientes por
     * producto.
     *
     * @param pModuleCode Codigo de modulo.
     * @param pProductCode Codigo de producto.
     * @param pSubproductCode Codigo de subproducto.
     * @param pPersontype Tipo de persona.
     * @return List<TgeneSubprodClientData>
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List<TgeneBaseRateDetail> find(EntityManager pEntityManager, String currencycode, String baseratecatalog, String baseratecatalogcode)
            throws Exception {
        List<TgeneBaseRateDetail> ldata = null;
        Query qry = pEntityManager.createQuery(TgeneBaseRateDetail.JPQL_RATEDETAIL);
        qry.setParameter("currencycode", currencycode);
        qry.setParameter("baseratecatalog", baseratecatalog);
        qry.setParameter("baseratecatalogcode", baseratecatalogcode);
        ldata = qry.getResultList();
        return ldata;
    }
    private static final String JPQL_RATEDETAIL_VIGENTS = " from TgeneBaseRateDetail tdet " + " where tdet.pk.currencycode = :currencycode "
            + " and tdet.pk.baseratecatalog = :baseratecatalog"
            + " and tdet.pk.baseratecatalogcode = :baseratecatalogcode and tdet.expirationdate>=:workingdate";

    /**
     * Metodo que entrega una lista de datos requeridos de clientes por
     * producto.
     *
     * @param pModuleCode Codigo de modulo.
     * @param pProductCode Codigo de producto.
     * @param pSubproductCode Codigo de subproducto.
     * @param pPersontype Tipo de persona.
     * @return List<TgeneSubprodClientData>
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List<TgeneBaseRateDetail> findVigents(EntityManager pEntityManager, String currencycode, String baseratecatalog,
            String baseratecatalogcode, Date workingdate) throws Exception {
        Query qry = pEntityManager.createQuery(TgeneBaseRateDetail.JPQL_RATEDETAIL_VIGENTS);
        qry.setParameter("currencycode", currencycode);
        qry.setParameter("baseratecatalog", baseratecatalog);
        qry.setParameter("baseratecatalogcode", baseratecatalogcode);
        qry.setParameter("workingdate", workingdate);
        return qry.getResultList();
    }
}
