import functools
import json
import os.path
import sys
import threading
import time

if getattr(sys, 'frozen', False):
    # 打包后的 exe
    os.chdir(os.path.dirname(sys.executable))
else:
    # 普通 Python 脚本
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

from api.api_app import start_flask
from modify_folder.monitor_file import start_watchdog
from tools.logger_handle import logger
from tools.serve_client import ServerClient
from config import *


def ApplicationInstance(func):
    @functools.wraps(func)
    def fun(*args, **kwargs):
        import socket
        try:
            global s
            s = socket.socket()
            host = socket.gethostname()
            s.bind((host, 60123))
        except:
            logger.error('不能重复打开已存在的程序')
            return None
        return func(*args, **kwargs)

    return fun


# 启动所有后台服务
@ApplicationInstance
def start_all_services(serve_client, work_path):
    # 启动 Flask 服务
    threading.Thread(target=start_flask, args=[serve_client, work_path], daemon=True).start()
    # 启动文件监控
    threading.Thread(target=start_watchdog, args=[serve_client, work_path], daemon=True).start()
    logger.info('server running')
    while True:
        time.sleep(10)
        a = 0


if __name__ == "__main__":

    # if not os.path.exists(f'{dl_code}:\\ProgramData\\OfficeAssistant\\config.json'):
    #     logger.error('"config.json" is not find')
    #     sys.exit(0)
    #
    with open(f'/ProgramData/OfficeAssistant/config.json', 'r', encoding='utf-8') as f:
    # with open(f'config.json', 'r', encoding='utf-8') as f:
        args = json.load(f)
    args['worker_path'] = args['worker_path'].replace('\\\\', '\\')
    if not (args.get('username') and args.get('password')):
        logger.error('The config is missing critical information')
        sys.exit(0)

    client = ServerClient(TARGET_URL, args['username'], args['password'])
    if not os.path.exists(os.path.join(args['worker_path'], args['username'])):
        os.makedirs(os.path.join(args['worker_path'], args['username']))

    start_all_services(client, os.path.join(args['worker_path'], args['username']))
