package cn.quant.baa.pay.component;

import cn.quant.spring.util.IdentitySequencer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author hechao
 * @description
 * @date 2020/7/24 13:45
 * @modify 2020/7/24 13:45 by hechao
 */
@Component
public class Sequencer {

    private final AtomicLong INDEX = new AtomicLong(1L);

    @Autowired
    private IdentitySequencer sequencer;

    public Long nextId() {
        return nextId(INDEX.addAndGet(1L));
    }

    public Long nextId(long flake) {
        return sequencer.nextId(flake % 225L);
    }

    public int partitionKey(long id) {
        return (int) ((id >> 8 << 8) ^ id);
    }

    public Long workerId() {
        return sequencer.workerId();
    }

    public Long index() {
        return INDEX.get();
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Sequencer{")
                .append("INDEX = ").append(index())
                .append(",sequencer = ").append(sequencer)
                .append("}");
        return sb.toString();
    }
}