#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
射箭ID生成器
为每次射箭生成唯一ID，格式：{timestamp_ms}_{counter}
"""
from maix import time
import threading


class ShotIDGenerator:
    """射箭ID生成器（单例）"""
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super(ShotIDGenerator, cls).__new__(cls)
                    cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        if self._initialized:
            return
        
        self._counter = 0
        self._last_timestamp_ms = 0
        self._lock = threading.Lock()
        
        self._initialized = True
    
    def generate_id(self, device_id=None):
        """
        生成唯一的射箭ID
        
        Args:
            device_id: 可选的设备ID，如果提供则包含在ID中（格式：{device_id}_{timestamp_ms}_{counter}）
                       如果不提供，则使用简单格式（格式：{timestamp_ms}_{counter}）
        
        Returns:
            str: 唯一的射箭ID
        """
        with self._lock:
            current_timestamp_ms = time.ticks_ms()
            
            # 如果时间戳相同，增加计数器；否则重置计数器
            if current_timestamp_ms == self._last_timestamp_ms:
                self._counter += 1
            else:
                self._counter = 0
                self._last_timestamp_ms = current_timestamp_ms
            
            # 生成ID
            if device_id:
                shot_id = f"{device_id}_{current_timestamp_ms}_{self._counter}"
            else:
                shot_id = f"{current_timestamp_ms}_{self._counter}"
            
            return shot_id
    
    def reset(self):
        """重置计数器（通常不需要调用）"""
        with self._lock:
            self._counter = 0
            self._last_timestamp_ms = 0


# 创建全局单例实例
shot_id_generator = ShotIDGenerator()





