# -*- coding: utf-8 -*-
import datetime
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from scriptBase.comon import *
import pyautogui
import base64
import threading
from yys_task import *
from collections import deque
import json

app = Flask(__name__)
socketio = SocketIO(app)
event = threading.Event()
g_status = ''
last_time = 0.0
task_queue = deque()
last_process = ''
isGameBegin = True
autoTask = None
isReset = False

def thread_runTask():
    global last_process
    global task_queue,isReset
    while True:
        if event.is_set():
            task_queue.clear()
        if len(task_queue) != 0:
            task = task_queue[-1]
            task_queue.pop()
            last_process = task.name
            task.run()
            myTimeSleep_small()
        else:
            myTimeSleep_big()
        if isReset:
            isReset = False
            restart_game()


@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def handle_connect():
    print('Client connected')

@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')

def send_hint(msg):#数组信息
    emit('processing_hint', msg)

def send_status(msg):#软件执行状态
    global g_status
    try:
        if msg == '':
            emit('processing_status', g_status)
            return
        else:
            g_status = msg
        
        if msg == "结束":
            event.clear()
        emit('processing_status', msg)
    except:
        return
    
def send_todo():#软件执行状态
    try:
        if msg == '':
            emit('processing_status', g_status)
            return
        else:
            g_status = msg
        
        if msg == "结束":
            event.clear()
        emit('processing_status', msg)
    except:
        return


@socketio.on('monitor_begin')
def monitor_begin():
    global last_time, last_process
    current_time = time.time()
    elapsed_time = current_time - last_time
    if elapsed_time < 0.5:
        return
    last_time = current_time
    screenshot = pyautogui.screenshot()
    binary_img = binarize_image(screenshot)
    compressed_data = compress_image(binary_img)
    
    image_data_base64 = base64.b64encode(compressed_data).decode('utf-8')
    socketio.emit('image_data', image_data_base64)
    task_arr = []
    if not event.is_set():
        task_arr.append(last_process)
    for item in reversed(task_queue):
        task_arr.append(item.name)
    send_hint(json.dumps(task_arr, ensure_ascii=False))
    send_status('')
    #print("send img")

@socketio.on('end_script')
def handle_end_script():
    event.set()

@socketio.on('end_game')
def handle_end_game():
    event.set()
    task_close_game()
    send_status("结束")
    event.clear()

@socketio.on('beigin_baigui')
def handle_beigin_baigui():
    task_queue.append(task_baigui())

@socketio.on('get_title')
def handle_get_title():
    str = task_getComputerName()
    dst = str + ' machine'
    emit('processing_title', dst)

@socketio.on('reset_script')
def handle_reset_script():
    python = sys.executable
    while '--reset' in sys.argv:
    # 从 sys.argv 列表中删除 --reset 参数
        sys.argv.remove('--reset')
    os.execl(python, python, *sys.argv)

@socketio.on('restart_game')
def handle_restart_game():
    python = sys.executable
    os.execl(python, python, *sys.argv, '--reset')

def restart_game():
    global isGameBegin, autoTask
    isGameBegin = False
    while True:
        task_close_game()
        if True == task_start_game():
            break
        else:
            send_status("启动失败")
    isGameBegin = True
    send_status("结束")
    auto_task(None)


@socketio.on('begin_tansuo')
def handle_begin_tansuo(data):
    pageNum = data['pageNum'], timesNum = data['timesNum']
    for i in range(1, timesNum + 1):
        task_queue.append(task_tansuo(pageNum))

@socketio.on('begin_teamer')
def handle_begin_teamer():
    task_queue.appendleft(task_fightzuidui())


@socketio.on('begin_yuhun')
def handle_begin_yuhun():
    task_queue.appendleft(task_yuhun())

@socketio.on('begin_tupo')
def handle_begin_tupo():
    task_queue.append(task_topo(3))

@socketio.on('begin_AddPersion')
def handle_begin_AddPersion():
    task_queue.append(task_AddPerson(20))

@socketio.on('begin_jiyang')
def handle_begin_jiyang():
    task_queue.append(task_jiyang())

@socketio.on('begin_zhaohuan')
def handle_begin_zhaohuan():
    task_queue.append(task_zhaohuan())

@socketio.on('begin_yeyuanhuo')
def handle_begin_yeyuanhuo():
    task_queue.append(task_yeyuanhuo())

def add_auto_task(pageNum):
    global isGameBegin
    tmp_num = 0
    ten_pm = datetime.time(4, 0, 0)
    three_am = datetime.time(5, 0, 0)
    ten_am = datetime.time(10, 0, 0)
    while not event.is_set():
        if len(task_queue) != 0:
            time.sleep(5)
            continue
        current_time = datetime.datetime.now().time()
        if current_time > three_am and current_time < ten_am:
            task_close_game()
            time.sleep(1000)
            isGameBegin = False
            continue
        
        if isGameBegin == False:
            while True:
                task_close_game()
                if True == task_start_game():
                    break
            isGameBegin = True
            time.sleep(200)

        tansuo_times = random.randint(3, 6)
        tupo_times = 3
        liaotupo_times = 0
        if current_time < ten_pm:
            liaotupo_times = 2
        for i in range(liaotupo_times):
            task_queue.appendleft(task_topo(2, False))
        for i in range(tansuo_times):
            task_queue.appendleft(task_tansuo(pageNum))
        for i in range(tupo_times):
            task_queue.appendleft(task_topo(2))
        task_queue.appendleft(task_jiyang())
    task_queue.clear()
    send_status(f'自动模式结束')
    event.clear()
        
        

@socketio.on('begin_auto')
def handle_auto(data):
    auto_task(data)

def auto_task(data):
    global autoTask
    if data == None:
        pageNum = 28
    else:
        pageNum = data['pageNum']
    send_status(f'开始自动模式')
    autoTask = threading.Thread(target=add_auto_task, args=(pageNum,))#启动线程往里面添加任务
    autoTask.daemon = True
    autoTask.start()


@socketio.on('begin_daoguan')
def handle_begin_daoguan():
    while not event.is_set():
        task_daoguan()
    send_status("结束")


@socketio.on('begin_douji')
def handle_begin_douji():
    task_queue.append(task_douji(20))

@socketio.on('begin_chaoguiwang')
def handle_begin_chaoguiwang():
    task_queue.append(task_chaoguiwang())


if __name__ == '__main__':
    init()
    if '--reset' in sys.argv:
        isReset = True
        print("需要重启游戏")
    runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
    runTask.daemon = True
    runTask.start()
    
    socketio.run(app, host= '0.0.0.0', debug=True)
