# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved.
# OpenOLC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         `http://license.coscl.org.cn/MulanPSL2`
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

import threading
from typing import Dict

from olc.control.context.context import OlcContext


class OlcRequestRegistry:
    _instance = None
    _lock = threading.Lock()

    def __init__(self):
        # 后续修改为自排序结果
        self._requests: Dict[str, OlcContext] = {}
        self._lock = threading.Lock()

    @classmethod
    def get_instance(cls) -> "OlcRequestRegistry":
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = cls()
        return cls._instance

    def register(self, context: OlcContext) -> None:
        with self._lock:
            self._requests[context.request_id] = context

    def unregister(self, request_id: str) -> None:
        with self._lock:
            if request_id in self._requests:
                del self._requests[request_id]


    def cancel_newest_request(self, count: int) -> None:
        with self._lock:
            sorted_requests = sorted(self._requests.values(), key=lambda ctx: ctx.start_time, reverse=True)
            to_cancel = sorted_requests[:count]

            for request in to_cancel:
                request.is_cancelled = True