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

HOST = "192.168.0.7"
PORT = 40004
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):
    with open(PATH, "r", encoding="utf-8") as f:
        new_data = json.load(f)
    cdata = binascii.hexlify(line)
    ddata = cdata.decode("utf-8").upper()
    edata = hexspace(ddata, 2)
    path_pic = r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\Scorebug Indicators"

    if len(edata.split()) in [32, 33, 40]:
        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}.{milliseconds}"
        )
        active_temp = temp_new[
            9
        ]  # 133 - таймер идёт | 132 - таймер стоит | 128 - не игровое время стоит | 129 - не игровое время идёт

        if temp_new[31] not in [2]:
            time_attack = (
                temp_new[29] if temp_new[29] > 4 else f"{temp_new[29]}.{temp_new[30]}" if f"{temp_new[29]}.{temp_new[30]}" != "0.0" else ""
            )
            path_pic = path_pic + ("\\24Sec_Orange.png" if temp_new[29] > 4 else "\\24Sec_Red.png" if f"{temp_new[29]}.{temp_new[30]}" != "0.0" else "\\24Sec_empty.png")
        else:
            time_attack = ""  # temp_new[-2] == 1 - таймер идёт | 2 - таймер стоит | 0 - таймер не отображён
            path_pic = path_pic + "\\24Sec_empty.png"

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


    print(len(edata.split()), f"{str(edata):<120}__{timer_str:<7}__{time_attack:<3}__")


    try:
        with open(PATH, "w", encoding="utf-8") as file:
            json.dump(new_data, file, ensure_ascii=False, indent=4)
        # if ":" in new_data["timeGFX"]:
        #     time.sleep(.5)
        # else:
        #     time.sleep(.1)

    except Exception:
        pass


    # with open("timer_NN.csv", "a+") as file:
    #     file.write(str(temp_new))
    #     file.write("\n")
    # with open("timer_NN_2.csv", "a+") as file:
    #     file.write(str(temp_data))
    #     file.write("\n")
    # with open("timer_NN_3.csv", "a+") as file:
    #     file.write(str(ddata))
    #     file.write("\n")

    # time.sleep(0.1)


def read_logs():
    with open("timer_NN_1.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.sleep(.05)

                # 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_NN_{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)
            print(data)
            logging.debug(data)
            parse(data)

    except KeyboardInterrupt:
        tcp_socket.close()
        sys.exit(1)


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