package com.rjconsultores.ventaboletos.entidad;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;

import com.rjconsultores.ventaboletos.utilerias.ApplicationProperties;
import com.rjconsultores.ventaboletos.utilerias.CustomEnum;

public class CustomIdGenerator implements IdentifierGenerator, Configurable {

	private String seqName;
	private Integer tamanho;

	public Serializable generate(SessionImplementor session, Object object)
			throws HibernateException {

		Connection connection = session.connection();
		try {

			PreparedStatement ps = connection
					.prepareStatement("SELECT " + seqName + ".NEXTVAL AS NEXTVAL FROM DUAL");

			ResultSet rs = ps.executeQuery();

			if (rs.next()) {
				Integer id = rs.getInt("NEXTVAL");
				String newValue = id.toString();
				if (ApplicationProperties.getInstance().isCustomHabilitado(CustomEnum.HABILITAR_CUSTOM_SEQUENCE.getDescricao())) {
					newValue = "1" + (StringUtils.leftPad(id.toString(), tamanho, "0"));
				}
				return Integer.valueOf(newValue);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void configure(org.hibernate.type.Type arg0, Properties arg1, Dialect arg2) throws MappingException {
		setTamanho(Integer.valueOf(arg1.getProperty("tamanho")));
		setSeqName(arg1.getProperty("seqName"));
	}

	public Integer getTamanho() {
		return tamanho;
	}

	public void setTamanho(Integer tamanho) {
		this.tamanho = tamanho;
	}

	public String getSeqName() {
		return seqName;
	}

	public void setSeqName(String seqName) {
		this.seqName = seqName;
	}

}