package com.fp.general.keygen;

import java.io.Serializable;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.type.Type;

import com.fp.common.helper.BeanManager;
import com.fp.general.helper.PropertiesHelper;
import com.fp.sessionbeans.helper.Sequence;

public class SequenceKey extends AbstractKeyGen implements IdentifierGenerator, Configurable {
    public static final String SEQUENCE_NAME = "name";

    public static final String TYPE = "type";

    public static final String FILL = "fill";

    public static final String LENGTH = "length";

    private String sequenceName = null;

    private String fill = null;

    private Integer length = null;

    private Class<?> type = null;

    @Override
    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
        try {
            Sequence s = new Sequence();
            Serializable val = (Serializable) BeanManager.convertObject(s.getNextValue(this.sequenceName), this.type);
            if (this.isString(this.type) && (this.fill != null)) {
                val = this.fill((String) val, this.fill, this.length);
            }
            return val;
        } catch (Exception e) {
            throw new HibernateException(e);
        }
    }

    @Override
    public void configure(Type pType, Properties pParams, Dialect pD) throws MappingException {
        this.sequenceName = PropertiesHelper.getString(SequenceKey.SEQUENCE_NAME, pParams, null);
        try {
            this.fill = PropertiesHelper.getString(SequenceKey.FILL, pParams, null);
            this.length = PropertiesHelper.getInteger(SequenceKey.LENGTH, pParams);
        } catch (Exception e) {
            this.fill = null;
            this.length = null;
        }
        try {
            this.type = Class.forName(PropertiesHelper.getString(SequenceKey.TYPE, pParams, null));
        } catch (ClassNotFoundException e) {
            throw new MappingException(e);
        }
    }

}