package com.fp.persistence.pgeneral.charge;

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.GeneratedValue;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

import com.fp.dto.hb.HibernateBean;

/** Clase que implementa la entidad de Hibernate que hace referencia a la tabla TGENECHARGES */
@Entity(name = "TgeneCharges")
@Table(name = "TGENECHARGES")
public class TgeneCharges 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 TgeneCharges
     */
    @EmbeddedId
    @GenericGenerator(name = "seq_id", strategy = "com.fp.general.keygen.SubSequenceKey", parameters = {
            @Parameter(name = "sql", value = "select coalesce(max(RATESEQUENCE),0)+1 from TGENECHARGES " + "where BALANCETYPE=:btype "
                    + "and BALANCEGROUP=:bgroup " + "and MODULECODE=:modulecode " + "and STATUSCODE=:statuscode " + "and COMPANYCODE=:companycode "
                    + "and CURRENCYCODE = :currencycode"),
            @Parameter(name = "type", value = "java.lang.Integer"),
            @Parameter(name = "param", value = "btype,pk.balancetype;bgroup,pk.balancegroup;modulecode,pk.modulecode;statuscode,pk.statuscode;companycode,pk.companycode;currencycode,pk.currencycode"),
            @Parameter(name = "field", value = "ratesequence") })
    @GeneratedValue(generator = "seq_id")
    private TgeneChargesKey pk;

    @Column(name = "CHARGECURRENCYCODE", nullable = true)
    /**
     * Codigo de moneda en la que esta expresado el cargo
     */
    private String chargecurrencycode;

    @Column(name = "RATE", nullable = true)
    /**
     * Tasa anual a aplicar 
     */
    private BigDecimal rate;

    @Column(name = "PERCENT", nullable = true)
    /**
     * Porcentaje flat a aplicar
     */
    private BigDecimal percent;

    @Column(name = "MINVALUE", nullable = true)
    /**
     * Valor minimo a cobrar 
     */
    private BigDecimal minvalue;

    @Column(name = "MAXVALUE", nullable = true)
    /**
     * Valor maximo a cobrar
     */
    private BigDecimal maxvalue;

    @Column(name = "MINAMOUNT", nullable = true)
    /**
     * Monto minimo para buscar el cargo
     */
    private BigDecimal minamount;

    @Column(name = "MAXAMOUNT", nullable = true)
    /**
     * Monto maximo para buscar el cargo
     */
    private BigDecimal maxamount;

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

    /**
     * Contructor de TgeneCharges
     * 
     * @param pPk Clave Primaria del entity
     */
    public TgeneCharges(TgeneChargesKey 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 TgeneCharges
     */
    public static TgeneCharges find(EntityManager pEntityManager, TgeneChargesKey pKey) throws Exception {
        TgeneCharges obj = pEntityManager.find(TgeneCharges.class, pKey);
        return obj;
    }

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

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

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

    /**
     * Fija el valor de chargecurrencycode
     * 
     * @param pChargecurrencycode nuevo Valor de chargecurrencycode
     */
    public void setChargecurrencycode(String pChargecurrencycode) {
        this.chargecurrencycode = pChargecurrencycode;
    }

    /**
     * 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 percent
     * 
     * @return valor de percent
     */
    public BigDecimal getPercent() {
        return this.percent;
    }

    /**
     * Fija el valor de percent
     * 
     * @param pPercent nuevo Valor de percent
     */
    public void setPercent(BigDecimal pPercent) {
        this.percent = pPercent;
    }

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

    /**
     * Fija el valor de minvalue
     * 
     * @param pMinvalue nuevo Valor de minvalue
     */
    public void setMinvalue(BigDecimal pMinvalue) {
        this.minvalue = pMinvalue;
    }

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

    /**
     * Fija el valor de maxvalue
     * 
     * @param pMaxvalue nuevo Valor de maxvalue
     */
    public void setMaxvalue(BigDecimal pMaxvalue) {
        this.maxvalue = pMaxvalue;
    }

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

    /**
     * Fija el valor de minamount
     * 
     * @param pMinamount nuevo Valor de minamount
     */
    public void setMinamount(BigDecimal pMinamount) {
        this.minamount = pMinamount;
    }

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

    /**
     * Fija el valor de maxamount
     * 
     * @param pMaxamount nuevo Valor de maxamount
     */
    public void setMaxamount(BigDecimal pMaxamount) {
        this.maxamount = pMaxamount;
    }

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

    /**
     * Implementacion del metodo hashCode de la la entidad TgeneCharges
     * 
     * @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 TgeneCharges */
    @Override
    public Object createInstance() {
        TgeneCharges instance = new TgeneCharges();
        instance.setPk(new TgeneChargesKey());
        return instance;
    }

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

    // Metodos manuales

    public boolean equalsWithoutSequence(Object rhs) {
        if (rhs == null) {
            return false;
        }
        if (!(rhs instanceof TgeneCharges)) {
            return false;
        }
        TgeneCharges that = (TgeneCharges) rhs;
        if ((this.getPk() == null) || (that.getPk() == null)) {
            return false;
        }

        TgeneChargesKey thispk = this.getPk();
        TgeneChargesKey thatpk = that.getPk();

        if (thatpk == null) {
            return false;
        }
        if (!(thatpk instanceof TgeneChargesKey)) {
            return false;
        }
        if ((thispk.getBalancetype() == null) || (thatpk.getBalancetype() == null)) {
            return false;
        }
        if (!thispk.getBalancetype().equals(thatpk.getBalancetype())) {
            return false;
        }
        if ((thispk.getBalancegroup() == null) || (thatpk.getBalancegroup() == null)) {
            return false;
        }
        if (!thispk.getBalancegroup().equals(thatpk.getBalancegroup())) {
            return false;
        }
        if ((thispk.getModulecode() == null) || (thatpk.getModulecode() == null)) {
            return false;
        }
        if (!thispk.getModulecode().equals(thatpk.getModulecode())) {
            return false;
        }
        if ((thispk.getStatuscode() == null) || (thatpk.getStatuscode() == null)) {
            return false;
        }
        if (!thispk.getStatuscode().equals(thatpk.getStatuscode())) {
            return false;
        }
        if ((thispk.getCompanycode() == null) || (thatpk.getCompanycode() == null)) {
            return false;
        }
        if (!thispk.getCompanycode().equals(thatpk.getCompanycode())) {
            return false;
        }
        if ((thispk.getCurrencycode() == null) || (thatpk.getCurrencycode() == null)) {
            return false;
        }
        if (!thispk.getCurrencycode().equals(thatpk.getCurrencycode())) {
            return false;
        }
        return true;
    }

    /** Sentencia que devuelve un registro de TgeneCharges. */
    private static final String HQL_CHARGES = "from TgeneCharges tcharges  " + " where tcharges.pk.balancetype = :balancetype "
            + " and tcharges.pk.balancegroup = :balancegroup " + " and tcharges.pk.modulecode = :modulecode "
            + " and tcharges.pk.statuscode = :statuscode " + " and tcharges.pk.companycode = :companycode "
            + " and tcharges.pk.currencycode = :currencycode " + " and :amount between tcharges.minamount and tcharges.maxamount ";

    /**
     * Metodo que entrega la definicion de cargos generales.
     * 
     * @param pBalanceType Codigo de tipo de saldo a entregar buscar cargo.
     * @param pBanceGroup Codigo de tipo grupo de balance a entregar buscar cargo.
     * @param pModuleCode Codigo de modulo asociado al estatus de la cuenta a buscar el cargo.
     * @param pStatusCode Codigo de estatus de la cuenta a buscar el saldo.
     * @param pComapny Codigo de compania de la cuenta a buscar le cargo.
     * @param pCurrency Codigo de moneda de la cuenta a buscar le cargo.
     * @param pAmount Monto base con el cual se obtiene el cargo.
     * @return TgeneCharges
     * @throws Exception
     */
    public static TgeneCharges find(EntityManager pEntitymanager, String pBalanceType, String pBanceGroup, String pModuleCode, String pStatusCode,
            Integer pComapny, String pCurrency, BigDecimal pAmount) throws Exception {
        TgeneCharges obj = null;
        Query qry = pEntitymanager.createQuery(TgeneCharges.HQL_CHARGES);
        qry.setParameter("balancetype", pBalanceType);
        qry.setParameter("balancegroup", pBanceGroup);
        qry.setParameter("modulecode", pModuleCode);
        qry.setParameter("statuscode", pStatusCode);
        qry.setParameter("companycode", pComapny);
        qry.setParameter("currencycode", pCurrency);
        qry.setParameter("amount", pAmount);
        try {
            obj = (TgeneCharges) qry.getSingleResult();
        } catch (NoResultException e) {
            return obj;
        }
        return obj;
    }

    /** Sentencia que devuelve una lista de TgeneSubProductCharges por compania. */
    private static final String JQL_CHARGES_BY_MODULE = "from TgeneCharges tchar  " + " where tchar.pk.modulecode = :modulecode ";

    /**
     * Metodo que entrega la definicion de cargos definidos por subproducto.
     * 
     * @param pCompany Codigo de compania.
     * @return List<TgeneSubProductCharges>
     * @throws Exception
     */
    @SuppressWarnings(com.fp.common.helper.Constant.VUNCHECKED)
    public static List<TgeneCharges> findByModule(EntityManager pEntityManager, String pModuleCode) {
        List<TgeneCharges> list = null;
        Query qry = pEntityManager.createQuery(TgeneCharges.JQL_CHARGES_BY_MODULE);
        qry.setParameter("modulecode", pModuleCode);
        list = qry.getResultList();
        return list;
    }
}
