# -*- coding: utf-8 -*-

import urllib
import webview
# 假设 get_cookie 函数在这个文件中
# 确保 获取cookie.py 文件已更新，特别是清理 '|' 字符的部分
from 获取cookie import get_cookie  # 导入 get_cookie 函数
import os
import re
import sqlite3
import sys
import json
import time
import pickle
import requests
from datetime import datetime
import logging
import random
import websocket
from urllib.parse import unquote
import gzip
from protobuf.douyin import *
import execjs
import hashlib
import urllib.parse
from threading import Thread
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
session = requests.session()

# ... 已有代码 ...

class DouyinLiveWebFetcher:
    def __init__(self, live_url, roomId, Cookie, account_url_part):
        self.live_url = live_url
        self.roomId = roomId
        self.Cookie = Cookie
        self.account_url_part = account_url_part
        self.ws = None  # 用于存储 WebSocket 实例
        self.is_running = False  # 用于跟踪监听状态

    # 启动
    def start(self):
        self.is_running = True
        self._connectWebSocket()

    # 结束
    def stop(self):
        if self.is_running:
            self.is_running = False
            if self.ws:
                self.ws.close()  # 关闭 WebSocket 连接
            print(f"停止监听账号: {self.account_url_part}")

    def _connectWebSocket(self):
        """
        连接抖音直播间websocket服务器，请求直播间数据
        """
        try:
            self.ws = websocket.WebSocketApp(
                url="your_websocket_url",  # 替换为实际的 WebSocket URL
                on_open=self._wsOnOpen,
                on_message=self._wsOnMessage,
                on_error=self._wsOnError,
                on_close=self._wsOnClose
            )
            self.ws.run_forever()
        except Exception as e:
            print(f"连接 WebSocket 出错: {e}")
            raise  # 重新抛出异常，以便上层处理

    # ... 已有代码 ...

class Api:
    def __init__(self):
        self.monitor_instances = {}  # 用于存储监听实例

    # ... 已有代码 ...

    # 监控账号
    def monitor_account(self, url_part, username):
        try:
            # 假设这里获取到 live_url、roomId 和 Cookie
            live_url = "your_live_url"
            roomId = "your_roomId"
            Cookie = "your_cookie"
            fetcher = DouyinLiveWebFetcher(live_url, roomId, Cookie, url_part)
            self.monitor_instances[url_part] = fetcher
            thread = Thread(target=fetcher.start)
            thread.start()
            return True
        except Exception as e:
            print(f"启动监听出错: {e}")
            return False

    # 停止监听
    def stop_monitoring(self, url_part):
        """
        停止指定 url_part 账号的监听。
        参数: url_part (str) - 要停止监听的账号的 url_part
        返回: bool - 成功停止返回 True，失败返回 False
        """
        try:
            if url_part in self.monitor_instances:
                fetcher = self.monitor_instances[url_part]
                fetcher.stop()
                del self.monitor_instances[url_part]
                return True
            return False
        except Exception as e:
            print(f"停止监听出错: {e}")
            return False

    # ... 已有代码 ...

run_path = os.path.dirname(os.path.realpath(sys.argv[0]))

if __name__ == '__main__':
    # ... 已有代码 ...
    api = Api()

    window_html = os.path.join(run_path, 'index', 'live-management.html')
    # 在 create_window 中设置 api 对象，以便 JS 访问
    window = webview.create_window('直播管理系统', window_html, js_api=api, min_size=(1200, 800))

    # 启动 webview。启动后，界面将显示。
    # live-management.html 中的 JS 代码应在 DOM 准备就绪且 pywebview api 可用后调用 get_initial_accounts()
    webview.start(debug=False)