import os
import sys

import webview
import argparse
from api.api import API
from config.config import Config
from utils.utils import send_notifycation

from pystray import MenuItem as item
import pystray
from PIL import Image
import threading
import time

import requests
from io import BytesIO



# 前端页面目录
if sys.flags.dev_mode:
    MAIN_DIR = os.path.join("..", "dist")  # 开发环境
    DEBUG = True
else:
    MAIN_DIR = os.path.join(".", "web")  # 生产环境
    DEBUG = False


def WebViewApp(port,dev=False):
    api = API()    # 本地接口
    cfg = Config()    # 配置文件
    def detect():
        api.detectThreading()
        global timer
        timer = threading.Timer(0.25, detect)  # 在回调函数中再次启动定时器
        timer.start()  # 启动定时器
    def exitProgram():
        icon.stop()
        print("exitProgram")
        global timer
        timer.cancel()
    def action():
        global timer
        timer.cancel()
        icon.stop()
        # icon.visible = False
        if(dev):
            window = webview.create_window(cfg.appName, 'http://localhost:'+str(port)+'/',js_api=api)
            webview.start(debug=True, http_server=True)    # 启动窗口
        else:
            template = os.path.join(MAIN_DIR, "index.html")    # 设置页面，可以指向远程或本地
            window = webview.create_window(title=cfg.appName, url=template, js_api=api)    # 创建窗口
            api.window=window    # 本地接口
            webview.start(debug=DEBUG, http_server=True)    # 启动窗口
    timer = threading.Timer(0.25, detect)  # 在回调函数中再次启动定时器
    timer.start()  # 启动定时器
    response = requests.get('http://docs.marlene.top/demo/model/logo.png')
    response = response.content
    BytesIOObj = BytesIO()
    BytesIOObj.write(response)
    image = Image.open(BytesIOObj)
    menu = (item('打开主页面', action), item('退出', exitProgram))
    icon = pystray.Icon("name", image, "EMC", menu)
    icon.run()
    


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--port',
        type=str,
        default='3333',
        help="端口号")
    parser.add_argument(
        '--dev',
        type=str,
        default='False',
        help="开发模式")
    args = parser.parse_args()
    WebViewApp(args.port,args.dev=='True')
    
