# Copyright 2022-2024 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging, queue, threading
from typing import Dict
from .Subscription import Subscription
from .TFSControllerSettings import TFSControllerSettings

LOGGER = logging.getLogger(__name__)

class Subscriptions:
    def __init__(self) -> None:
        self._terminate = threading.Event()
        self._lock      = threading.Lock()
        self._subscriptions : Dict[str, Subscription] = dict()

    def add_subscription(self, tfs_ctrl_settings : TFSControllerSettings) -> None:
        device_uuid = tfs_ctrl_settings.device_uuid
        with self._lock:
            subscription = self._subscriptions.get(device_uuid)
            if (subscription is not None) and subscription.is_running: return
            subscription = Subscription(tfs_ctrl_settings, self._terminate)
            self._subscriptions[device_uuid] = subscription
            subscription.start()

    def remove_subscription(self, device_uuid : str) -> None:
        with self._lock:
            subscription = self._subscriptions.get(device_uuid)
            if subscription is None: return
            if subscription.is_running: subscription.stop()
            self._subscriptions.pop(device_uuid, None)

    def stop(self):
        self._terminate.set()
        for device_uuid in self._subscriptions:
            self.remove_subscription(device_uuid)
