package com.qmth.boot.redis.uid;

import com.qmth.boot.core.uid.UidGenerator;
import com.qmth.boot.core.uid.service.UidMachineService;
import com.qmth.boot.redis.constant.RedisConstant;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

@Component("uidMachineService")
public class RedisMachineService implements UidMachineService, RedisConstant {

    private Logger log = LoggerFactory.getLogger(RedisMachineService.class);

    private RedissonClient redissonClient;

    private int machineId;

    public RedisMachineService(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
        this.machineId = -1;
        for (int i = 0; i <= UidGenerator.MAX_MACHINE_ID; i++) {
            if (redissonClient.getLock(MACHINE_ID_PREFIX.concat(KEY_SEPARATOR).concat(String.valueOf(i))).tryLock()) {
                machineId = i;
                break;
            }
        }
        if (machineId > -1) {
            log.info("Redis machine service inited, machineId=" + machineId);
        } else {
            throw new RuntimeException("Get machineId from redis faile");
        }
    }

    @Override
    public int getMachineId() {
        return machineId;
    }

    @PreDestroy
    public void destroy() {
        if (machineId > -1) {
            redissonClient.getLock(MACHINE_ID_PREFIX.concat(KEY_SEPARATOR).concat(String.valueOf(machineId)))
                    .unlockAsync();
        }
        log.info("Redis machine service destroy.");
    }
}
