package com.fp.persistence.pgeneral.gene;

import java.io.Serializable;
import java.lang.reflect.Field;

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

import com.fp.dto.hb.HibernateBean;
import com.fp.general.exception.GeneralException;

/**
 * Clase que implementa la entidad de Hibernate que hace referencia a la tabla
 * TGENEBRANCH
 */
@Entity(name = "TgeneBranch")
@Table(name = "TGENEBRANCH")
public class TgeneBranch 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 TgeneBranch
	 */
	@EmbeddedId
	private TgeneBranchKey pk;
	@Version
	@Column(name = "RECORDVERSION", nullable = true)
	/**
	 * Optimistic locking del registro
	 */
	private Integer recordversion;

	@Column(name = "DESCRIPTION", nullable = true)
	/**
	 * Nombre de la sucursal
	 */
	private String description;

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

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

	/**
	 * Entrega la Clave primaria de TgeneBranch
	 * 
	 * @return El objeto que referencia a la Clave primaria de TgeneBranch
	 */
	public TgeneBranchKey getPk() {
		return pk;
	}

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

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

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

	/**
	 * Obtiene el valor de description
	 * 
	 * @return valor de description
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * Fija el valor de description
	 * 
	 * @param pDescription
	 *            nuevo Valor de description
	 */
	public void setDescription(String pDescription) {
		description = pDescription;
	}

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

	/**
	 * Implementación del metodo hashCode de la la entidad TgeneBranch
	 * 
	 * @return el hashCode la instancia
	 */
	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ón toString */
	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ón de la creación de un bean en blanco TgeneBranch */
	public Object createInstance() {
		TgeneBranch instance = new TgeneBranch();
		instance.setPk(new TgeneBranchKey());
		return instance;
	}

	/**
	 * Clona la entidad TgeneBranch
	 * 
	 * @see com.fp.dto.hb.HibernateBean#cloneMe()
	 */
	public Object cloneMe() throws CloneNotSupportedException {
		TgeneBranch p = (TgeneBranch) this.clone();
		p.setPk((TgeneBranchKey) this.pk.cloneMe());
		return p;
	}
	
	//Metodos manuales.
    /** Sentencia que devuelve un registro de TgeneBranch.*/
    private static final String JPQL_BRANCH =
            "from TgeneBranch tb  "
            + " where tb.pk.branchcode = :branch "
            + " and tb.pk.companycode = :company ";

    /**
     * Metodo que entrega datos de una sucursal definidos en TgeneBranch.
     * @param pBranch	Codigo de sucursal.
     * @param pCompany	Compania a la que pertenece la cuenta.
     * @return	TgeneBranch
     * @throws Exception
     */
    public static TgeneBranch find(EntityManager pEntityManager ,Integer pBranch, Integer pCompany) throws Exception {
        Query qry = pEntityManager.createQuery(JPQL_BRANCH);
        qry.setParameter("branch", pBranch);
        qry.setParameter("company", pCompany);        
        try {
        	return (TgeneBranch) qry.getSingleResult();	
		} catch (NoResultException e) {
            throw new GeneralException("GENE-0001", "SUCURSAL NO DEFINIDA EN TGENEBRANCH: BRANCH:{0} COMPANY:{1}",
                    pBranch, pCompany);
		}
    }
	
}
