#!/usr/bin/env python
# encoding: utf-8
"""
@author: simin. Gong
@license: (C) Copyright 2013-2023 Spacemit Corporation Limited.
@contact: simin.gong@spacemit.com
@file: AiDomainNamespace.py
@date: 2024/12/5 09:28 
@desc:
"""
import threading

from flask_socketio.namespace import Namespace

from ai_tool.plugins import register_plugin_wrapper

lock = threading.Lock()

class AiDomainNamespace(Namespace):

    def __init__(self, namespace=None):
        super(AiDomainNamespace, self).__init__(namespace)
        self.plugin_cache = {}

    def on_connect(self):
        pass

    def on_start_plugin(self, data):
        plugin_name = data['plugin']
        with lock:
            if plugin_name in self.plugin_cache:
                self.commit_plugin_start(plugin_name)
                return
            if plugin_name not in register_plugin_wrapper:
                self.commit_plugin_stop(plugin_name)
                print(f'plugin {plugin_name} not support!')
                return
            self.stop_current_plugin()
            plugin_cls = register_plugin_wrapper[data['plugin'] ]
            plugin_obj = plugin_cls()
            plugin_obj.start()
            self.commit_plugin_start(plugin_name)
            self.plugin_cache[plugin_name] = plugin_obj
        for data in plugin_obj.get_date_queue():
            self.emit(f'{plugin_name}_data', {'frame': data[0], 'boxs': data[1]})
        print('plugin结束')

    def on_stop_plugin(self, data):
        plugin_name = data['plugin']
        with lock:
            if plugin_name not in self.plugin_cache:
                self.commit_plugin_stop(plugin_name)
                print(f'plugin {plugin_name} has not start!')
                return
            plugin_obj = self.plugin_cache[plugin_name]
            plugin_obj.stop()
            del self.plugin_cache[plugin_name]
            self.commit_plugin_stop(plugin_name)

    def stop_current_plugin(self):
        for plugin_name , plugin_obj in self.plugin_cache.items():
            plugin_obj.stop()
            self.commit_plugin_stop(plugin_name)
        self.plugin_cache = {}

    def commit_plugin_start(self, plugin_name):
        self.emit('plugin_start', {'plugin': plugin_name})


    def commit_plugin_stop(self, plugin_name):
        self.emit('plugin_stop', {'plugin': plugin_name})

    def on_disconnect(self):
        pass