# coding:utf-8
import tkinter as tk
from core.logger import LogLevel, PrintLog
from PIL import Image
import pystray
import threading

class MainEntry:
    def __init__(self, master):
        self.master = master
        self.master.title("Main Board")
        self.master.geometry("800x600")
        self.master.configure(bg="#f0f0f0")
        self.master.resizable(False, False)
        self.master.protocol("WM_DELETE_WINDOW", self.hide_window)
        self.qmt_enabled = False
        self.icon = None
        self.create_systray_icon()

    def create_systray_icon(self):
        # 加载图标文件（需确保路径正确）
        image = Image.open("logo.png")
        # 定义托盘菜单
        menu = (
            pystray.MenuItem('交易大师', None, enabled=False),
            pystray.MenuItem("  - 交易复盘", self.handler),
            pystray.MenuItem("  - 市场数据", self.handler),
            pystray.MenuItem("  - 快速下单", self.handler),
            pystray.MenuItem('策略交易', None, enabled=False),
            pystray.MenuItem("  - 交易看板", self.handler),
            pystray.MenuItem("  - 策略中心", None),
            pystray.MenuItem("  - 策略定制", None),
            pystray.MenuItem('实时数据', None, enabled=False),
            pystray.MenuItem("  - QMT (已关闭)" if not self.qmt_enabled else "  - QMT (已开启)", self.marketDataSwitch),
            pystray.Menu.SEPARATOR,
            pystray.MenuItem("  - 控制台", self.show_window, default=True),
            pystray.MenuItem("  - 设置", self.marketDataSwitch),
            pystray.MenuItem("  - 退出", self.quit_window)
        )
        
        if self.icon:
            self.icon.menu = menu
            self.icon.update_menu()
        else:
            # 创建托盘图标
            self.icon = pystray.Icon("name", image, "标题", menu)
            self.trayThread = threading.Thread(target=self.icon.run, daemon=True)
            self.trayThread.start()
        # 在后台线程运行托盘

    def marketDataSwitch(self):
        if self.qmt_enabled:
            self.qmt_enabled = False
            PrintLog(LogLevel.INFO, "QMT 市场数据已关闭")
        else:
            self.qmt_enabled = True
            PrintLog(LogLevel.INFO, "QMT 市场数据已开启")
        self.create_systray_icon()

    def handler(self):
        PrintLog(LogLevel.INFO, f"点击了")

    def hide_window(self):
        PrintLog(LogLevel.INFO, "隐藏主窗口")
        self.master.withdraw()  # 隐藏主窗口

    def show_window(self):
        self.icon.visible = True
        PrintLog(LogLevel.INFO, "显示主窗口")
        self.master.deiconify()  # 显示主窗口

    def quit_window(self, icon: pystray.Icon):
        icon.stop()
        PrintLog(LogLevel.INFO, "退出应用")
        self.master.quit()
        self.master.destroy()

    def run(self):
        self.master.mainloop()



