import sys
from socket import *
from datetime import datetime
import logging
import os
import time
import binascii
import requests


HOST = "192.168.127.254"
PORT = 1993
PATH = (
    r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\python\JSON\timer_basketball.json"
)


def hexspace(string, length):
    return " ".join(string[i : i + length] for i in range(0, len(string), length))


def parse(line):
    cdata = binascii.hexlify(line)
    ddata = cdata.decode("utf-8").upper()
    edata = hexspace(ddata, 2)

    if len(edata.split()) == 33:
        temp_data = edata.split()
        temp_new = [int(t, 16) for t in temp_data]
        minutes = temp_new[6]
        seconds = temp_new[7]
        milliseconds = temp_new[8]
        timer_str = (
            f"{minutes}:{seconds:02d}"
            if minutes != 0
            else f"{seconds:02d}.{milliseconds}"
        )
        active_temp = temp_new[
            9
        ]  # 133 - таймер идёт | 132 - таймер стоит | 128 - не игровое время стоит | 129 - не игровое время идёт

        if temp_new[-2] != 0:
            time_attack = (
                temp_new[-4] if temp_new[-4] > 4 else f"{temp_new[-4]}.{temp_new[-3]}"
            )
        else:
            time_attack = ""  # temp_new[-2] == 1 - таймер идёт | 2 - таймер стоит | 0 - таймер не отображён

        # print(f"{str(temp_new):<120}__{timer_str:<7}__{time_attack:<3}__")
    else:
        temp_data = edata.split()
        temp_new = [int(t, 16) for t in temp_data]

    # time.sleep(0.1)


def read_logs():
    with open("timer_NN_2023-12-20_18-17-29.log", "r") as file:
        # with open("timer_NN_test.log", "r") as file:
        temp_line = ""
        for line in file:
            parts = line.strip().split(" DEBUG ")
            if len(parts) == 2:
                timestamp = parts[0][1:]
                data = eval(parts[1])
                parse(data)
                time.sllep(0.1)

                # if len(eval(data)) > 30 and eval(data)[-7] == "00":
                #     time.sleep(.1)
                # else:
                #     time.sleep(1)


def main():
    current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    if not os.path.isdir("LOGS"):
        os.mkdir("LOGS")

    LogFileName = f"LOGS/timer_Chine_tcp_{current_time}.log"
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s %(levelname)s %(message)s",
        filename=LogFileName,
        filemode="w",
    )
    # new_data = {
    #     "timeGFX": "0:00",
    #     "time_attackGFX": "",
    #     "quarter": "0",
    #     "points1": "0",
    #     "points2": "0",
    #     "foul1": "0",
    #     "foul2": "0",
    #     "foul_pic1": "",
    #     "foul_pic2": "",
    #     "time_attac_pic": "",
    # }
    # with open(PATH, "w", encoding="utf-8") as file:
    #     json.dump([new_data], file, ensure_ascii=False, indent=4)

    try:
        tcp_socket = socket(AF_INET, SOCK_STREAM)
        tcp_socket.connect((HOST, PORT))
        data = str.encode("hello")
        tcp_socket.send(data)
        data = bytes.decode(data)
        while True:
            data = tcp_socket.recv(1024)
            logging.debug(data)
            cdata = binascii.hexlify(data)
            ddata = cdata.decode("utf-8").upper()
            edata = hexspace(ddata, 2)
            temp_data = edata.split()
            temp_new = [int(t, 16) for t in temp_data]
            # print(temp_new)
            timer = f"{temp_new[3]}:{temp_new[2]}"
            seconds = temp_new[5]
            milliseconds = str(temp_new[4])[0]
            if int(seconds) > 4:
                temp = float(f"{seconds}.{milliseconds}")
                if int(milliseconds) >= 5:
                    seconds = int(seconds) + 1
                else:
                    seconds = seconds
                timer_attack = seconds
                timer_color = "#59358A"
            else:
                timer_attack = f"{seconds}.{milliseconds}"
                timer_color = "#FF6A13"
            if temp_new[0] in [16, 24]:
                timer_attack = ""
                timer_color = "#000000"
            url = "http://127.0.0.1:8088/API/"
            params = {
                "Function": "SetText",
                "Input": 221,
                "SelectedName": "12sec.Text",
                "Value": timer_attack,
            }
            params1 = {
                "Function": "SetColor",
                "Input": 221,
                "SelectedName": "12SecBackground.Fill.Color",
                "Value": timer_color,
            }
            requests.get(url, params=params)
            requests.get(url, params=params1)
            print(
                f"data: {edata}",
                temp_new,
                timer,
                f"{seconds}.{milliseconds}, attack: {timer_attack}",
            )
    except KeyboardInterrupt:
        tcp_socket.close()
        sys.exit(1)


if __name__ == "__main__":
    try:
        main()
        # read_logs()
    except KeyboardInterrupt:
        sys.exit(1)
