<?php
/*
 * @author: CloudZA(云之安) <2922619853@qq.com>
 * @hitokoto: 一场秋雨一场凉，秋心酌满泪为霜。
 * Copyright (c) 2022 by CloudZA, All Rights Reserved.
 */

class SnowflakeIdWorker{
    /** 开始时间截 */
    const twepoch = 1651671982333;
    /** 机器id所占的位数 */
    const workerIdBits = 10;
    //支持的最大机器id，结果是1023 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
    const maxWorkerId = (-1 ^ (-1 << self::workerIdBits));
    //序列在id中占的位数
    const sequenceBits = 12;
    //机器ID向左移12位
    const workerIdShift = self::sequenceBits;
    //时间戳向左移22位(10+12)
    const timestampLeftShift = self::workerIdBits  + self::sequenceBits;
    //序列号值的最大值，这里为4095 (0b111111111111=0xfff=4095)
    const sequenceMask = (-1 ^ (-1 << self::sequenceBits));

    private static $sequence = 0;
    private static $lastTimestamp = -1;

    private static function nextId($workerId){
        $timestamp = self::timeGen();

        if($timestamp < self::$lastTimestamp){
            throw new Exception('Clock moved backwards');
        }

        if($timestamp == self::$lastTimestamp){
            self::$sequence = (self::$sequence + 1) & self::sequenceMask;
            if(self::$sequence == 0){
                $timestamp = self::tilNextMillis(self::$lastTimestamp);
            }
        }else{
            self::$sequence = 0;
        }

        self::$lastTimestamp = $timestamp;

        return (($timestamp - self::twepoch) << self::timestampLeftShift) |
            ($workerId << self::workerIdShift) |
            self::$sequence;
    }

    private static function tilNextMillis($lastTimestamp){
        $timestamp = self::timeGen();
        while($timestamp <= $lastTimestamp){
            $timestamp = self::timeGen();
        }
        return $timestamp;
    }

    private static function timeGen(){
        return (float)sprintf("%.0f", microtime(true) * 1000);
    }

    /**
     * @throws Exception
     */
    public static function generateId($workerId = 0){
        if($workerId < 0 || $workerId > self::maxWorkerId){
            throw new Exception('Invalid worker ID');
        }
        return self::nextId($workerId);
    }
}
