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


VERSION = "версия 2" # от 02.04.2024

host = "192.168.127.254"
port = 1993
ADDR = (host, port)
PATH = (
    r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\python\JSON\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}"
    if not os.path.isdir("LOGS"):
        os.mkdir("LOGS")
    with open(f"LOGS/{name}", "a") as file:
        file.write(message_with_time + "\n")


def parse(data, score1, score2):
    data = data.split("/")

    with open(PATH, "r", encoding="utf-8") as f:
        new_data = json.load(f)
    new_data = new_data[0]
    path_pic = r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\Scorebug Indicators"
    # print(data)
    diff1, diff2 = 0, 0
    try:
        if len(data) > 10:
            if data[4] == "NPR":
                new_data["quarter"] = data[5]
            if data[17] == "HCP":
                new_data["points1"] = data[18]
                if score1 != new_data["points1"]:
                    diff1 = int(new_data["points1"]) - int(score1)
                    score1 = new_data["points1"]
            if data[20] == "GCP":
                new_data["points2"] = data[21]
                if score2 != new_data["points2"]:
                    diff2 = int(new_data["points2"]) - int(score2)
                    score2 = new_data["points2"]
            if data[29] == "HCF":
                new_data["foul1"] = data[30]
                new_data["foul_pic1"] = path_pic + f"\\Home_{int(data[30])}.png"
            if data[32] == "GCF":
                new_data["foul2"] = data[33]
                new_data["foul_pic2"] = path_pic + f"\\Away_{int(data[33])}.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 not millisec.isdigit():
                        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]
                if score1 != new_data["points1"]:
                    diff1 = int(new_data["points1"]) - int(score1)
                    score1 = new_data["points1"]
            elif data[1] == "GCP":
                new_data["points2"] = data[2]
                if score2 != new_data["points2"]:
                    diff2 = int(new_data["points2"]) - int(score2)
                    score2 = new_data["points2"]
            elif data[1] == "HCF":
                new_data["foul1"] = data[2]
                new_data["foul_pic1"] = path_pic + f"\\Home_{int(data[2])}.png"
                if len(data) > 4 and data[4] == "GCF":
                    new_data["foul2"] = data[2]
                    new_data["foul_pic2"] = path_pic + f"\\Away_{int(data[2])}.png"
            elif data[1] == "GCF":
                new_data["foul2"] = data[2]
                new_data["foul_pic2"] = path_pic + f"\\Away_{int(data[2])}.png"
            elif data[1] == "TAI":
                if data[2] not in ["0", "-1"]:
                    new_data["time_attackGFX"] = str(int(data[2]))
                elif data[2] == "-1":
                    new_data["time_attackGFX"] = ""
                    new_data["time_attac_pic"] = path_pic + "\\24Sec_empty.png"
                if 0 < int(data[2]) <= 5:
                    new_data["time_attac_pic"] = path_pic + "\\24Sec_Red.png"
                else:
                    if int(data[2]) in [0, -1]:
                        new_data["time_attac_pic"] = path_pic + "\\24Sec_empty.png"
                    else:
                        new_data["time_attac_pic"] = path_pic + "\\24Sec_Orange.png"

        print(f'{diff1}, {diff2}, {new_data["timeGFX"]:<5}, {new_data["time_attackGFX"]:<3}, {new_data["points1"]:<3}, {new_data["points2"]:<3}, {new_data["foul1"]:<2}, {new_data["foul2"]:<2}')
    except Exception as ex:
        print(ex)
    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

    return score1, score2


def main():
    current_time = datetime.now().strftime("%d-%m-%Y_%H-%M-%S")

    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)
    score1, score2 = 0, 0

    try:
        while True:
            data = str.encode("hello")
            tcp_socket.send(data)
            data = bytes.decode(data)
            data = tcp_socket.recv(1024)
            data = data.decode("utf-8", errors="ignore")
            print(data)

            save_log(f"logs_mba_{VERSION}_{current_time}.txt", data)
            score1, score2 = parse(data, score1, score2)
    except KeyboardInterrupt:
        tcp_socket.close()
        sys.exit(1)


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