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

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


def parse(line):

    # if len(line) > 6:
    try:
        with open(PATH, "r", encoding="utf-8") as f:
            new_data = json.load(f)
        timer_bool = 0
        if b"\xf87" in line:
            temp_new = str(line.split(b"\xf87")[1])
        elif b"\xf88" in line:
            temp_new = str(line.split(b"\xf88")[1])
        elif b"\xf83" in line:
            temp_new = str(line.split(b"\xf83")[1])
            timer_bool = 1
        print(line)
        timer_temp = temp_new[4:8]
        # print(str(timer_temp) == '\\xf2')
        if timer_temp != "\\xf2":
            if timer_temp[-1] != " ":
                minutes = int(timer_temp[:2])
                seconds = timer_temp[2:]
                timer_str = f"{minutes}:{seconds}"
            else:
                seconds = int(timer_temp[0:2])
                milliseconds = int(timer_temp[2:])
                timer_str = f"{seconds}.{milliseconds}"
            if timer_bool == 1:
                quarter = temp_new[14]
                points1 = (temp_new[8:11]).strip()
                points2 = (temp_new[11:14]).strip()
                fouls1 = temp_new[15]
                fouls2 = temp_new[16]
                new_data[0]["points1"] = points1
                new_data[0]["points2"] = points2
                new_data[0]["foul1"] = fouls1
                new_data[0]["foul2"] = fouls2
                new_data[0]["quarter"] = quarter

            path_pic = r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\Scorebug Indicators"
            attack_display = temp_new[51:53]
            if attack_display == "30":
                time_attack = ""
                path_pic = path_pic + "\\24Sec_empty.png"
            else:
                word_to_int = "ABCDEFGHI@"
                time_attack_temp = temp_new[48:50]
                # print(time_attack_temp)
                # print(word_to_int.index(time_attack_temp[1])+1 if time_attack_temp[1] != '@' else '0')
                if time_attack_temp[1] in word_to_int:
                    time_attack = f"{time_attack_temp[0]}.{word_to_int.index(time_attack_temp[1])+1 if time_attack_temp[1] != '@' else '0'}"
                    path_pic = path_pic + "\\24Sec_Red.png"
                else:
                    time_attack = (
                        int(time_attack_temp)
                        if time_attack_temp != "  "
                        else time_attack_temp
                    )
                    path_pic = path_pic + "\\24Sec_Orange.png"
                if time_attack == "0.0":
                    time_attack = ""
                    path_pic = path_pic + "\\24Sec_empty.png"
            if timer_str == "0:00":
                timer_str = "0.0"

            new_data[0]["timeGFX"] = timer_str
            new_data[0]["time_attackGFX"] = time_attack
            new_data[0]["time_attac_pic"] = path_pic

            print(new_data[0]["timeGFX"], new_data[0]["time_attackGFX"])
            try:
                with open(PATH, "w", encoding="utf-8") as file:
                    json.dump(new_data, file, ensure_ascii=False, indent=4)
            except Exception:
                print(Exception)
                pass
            # logging.debug(new_data)
    except Exception as ex:
        print(ex)
        pass


def read_logs():
    with open(
        r"C:\Users\soule\Downloads\Telegram Desktop\timer_Megasport_Nport_2024-03-05_20-00-17.log",
        "r",
    ) as file:
        for line in file:
            parts = line.strip().split(" DEBUG ")
            if len(parts) == 2:
                timestamp = parts[0][1:]
                data = eval(parts[1])
                if b"\xf83" in data or b"\xf88" in data or b"\xf87" in data:
                    parse(data)
                    time.sleep(0.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_Megasport_Nport_{current_time}.log"
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s %(levelname)s %(message)s",
        filename=LogFileName,
        filemode="w",
    )
    new_data = {
        "timeGFX": "0.0",
        "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)
            # if b"\xf83" in data or b"\xf88" in data or b"\xf87" in data:
            parse(data)
    except KeyboardInterrupt:
        tcp_socket.close()
        sys.exit(1)


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