package com.galaxis.manatee.util.impl;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

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

/**
 * @author zcj
 * @version 0.1
 * @date 2020/1/8 11:53 下午
 */
public class GalaxisIdGenerator implements Configurable, IdentifierGenerator {
    /** 数据中心ID(0~31) */
    private long dataCenterId = 0L;

    @Override
    public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String[] a=addr.getHostName().split("-");
            dataCenterId =Long.parseLong(a[a.length-1]);
        }
        catch (Exception e){
            //10位长度最大值1023，这里简单写为1000，相信不会用到
            dataCenterId =1000L;
        }
    }

    public Serializable generate(SessionImplementor session, Object o) throws HibernateException {
        SnowflakeIdGenerator snowflakeIdWorker = SnowflakeIdGenerator.getSnowflakeIdGenerator(this.dataCenterId);
        return snowflakeIdWorker.nextId();
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        SnowflakeIdGenerator snowflakeIdWorker = SnowflakeIdGenerator.getSnowflakeIdGenerator(this.dataCenterId);
        return snowflakeIdWorker.nextId();
    }
}
