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


host = "10.0.0.57"
port = 50002
ADDR = (host, port)
PATH = "D:\\timer_basketball.json"


def save_log(name, data):
    current_time = datetime.now().strftime("%d-%m-%Y %H:%M:%S.%f")
    message_with_time = f"[{current_time}] {data}"
    with open(name, "a") as file:
        file.write(message_with_time + "\n")


def parse(data):
    data = data.split("/")

    with open(PATH, "r", encoding="utf-8") as f:
        new_data = json.load(f)
    new_data = new_data[0]
    path_pic = "D:\Графика\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\VTB_Fouls for scoreboard smaller"
    if len(data) > 10:
        if data[4] == "NPR":
            new_data["quarter"] = data[5]
        if data[17] == "HCP":
            new_data["points1"] = data[18]
        if data[20] == "GCP":
            new_data["points2"] = data[21]
        if data[29] == "HCF":
            new_data["foul1"] = data[30]
            new_data["foul_pic1"] = path_pic + f"\Home тАУ {int(data[30])} Foul.png" 
        if data[32] == "GCF":
            new_data["foul2"] = data[33]
            new_data["foul_pic2"] = path_pic + f"\Away тАУ {int(data[33])} Foul.png" 
    else:
        if data[1] == "TGI":
            if data[2] != "0":
                seconds = data[3] if len(data[3]) != 1 else f"0{data[3]}"
                new_data["timeGFX"] = f"{data[2]}:{seconds}"
            else:
                millisec = data[4]
                if millisec == "#":
                    millisec = "0"
                new_data["timeGFX"] = f"{data[3]}.{millisec}"
        elif data[1] == "NPR":
            new_data["quarter"] = data[2]
        elif data[1] == "HCP":
            new_data["points1"] = data[2]
        elif data[1] == "GCP":
            new_data["points2"] = data[2]
        elif data[1] == "HCF":
            new_data["foul1"] = data[2]
            new_data["foul_pic1"] = path_pic + f"\Home тАУ {int(data[2])} Foul.png" 
        elif data[1] == "GCF":
            new_data["foul2"] = data[2]
            new_data["foul_pic2"] = path_pic + f"\Away тАУ {int(data[2])} Foul.png" 
        elif data[1] == "TAI":
            if data[2] not in ["0", "-1"]:
                new_data["time_attackGFX"] = str(int(data[2]))
            if int(data[2]) <= 5:
                new_data["time_attac_pic"] = ""
            else:
                new_data["time_attac_pic"] = "empty"

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

    except Exception:
        pass


def read_logs():
    with open("logs_mba_1.txt", "r") as file:
        for line in file:
            parts = line.strip().split("] ")
            if len(parts) == 2:
                timestamp = parts[0][1:]
                data = parts[1]

                parse(data)

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


def main():
    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)





    # tcp_socket = socket(AF_INET, SOCK_STREAM)
    # tcp_socket.connect(ADDR)

    # try:
    #     while True:
    #         data = str.encode("hello")
    #         tcp_socket.send(data)
    #         data = bytes.decode(data)
    #         data = tcp_socket.recv(1024)
    #         data = data.decode()
    #         save_log("logs_mba_1.txt", data)
    #         parse(data)
    # except KeyboardInterrupt:
    #     tcp_socket.close()
    #     sys.exit(1)


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

