#!/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
import time
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 = {}
        self.get_ping = False
        # thread = threading.Thread(target=self.watch_ping, args=())
        # thread.start()

    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.stop_current_plugin()
                self.commit_plugin_stop(plugin_name)
                return
            plugin_obj = self.plugin_cache[plugin_name]
            plugin_obj.stop()
            del self.plugin_cache[plugin_name]
            self.commit_plugin_stop(plugin_name)

    def watch_ping(self):
        while True:
            time.sleep(4)
            if not self.get_ping:
                self.stop_current_plugin()
            self.get_ping = False

    def on_ping(self, data):
        pass

    def stop_current_plugin(self):
        if not self.plugin_cache:
            return
        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):
        print('浏览器断连，关闭ai插件!')
        self.stop_current_plugin()