import sys
import json
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"
)

session = requests.Session()
session.headers.update({"Connection": "keep-alive"})


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


def send_data(name, value):
    url = "http://127.0.0.1:8088/API/"
    par = "SetText" if name.split(".")[1] == "Text" else "SetImage"
    params = {
        "Function": par,
        "Input": 51,
        "SelectedName": name,
        "Value": value,
    }
    session.get(url, params=params)

def parse_new(line):
    try:
        with open(PATH, "r", encoding="utf-8") as f:
            new_data = json.load(f)
    except json.decoder.JSONDecodeError:
        new_data = [
            {
                "timeGFX": "0:00",
                "time_attackGFX": "",
                "quarter": "0",
                "points1": "0",
                "points2": "0",
                "foul1": "0",
                "foul2": "0",
                "foul_pic1": "",
                "foul_pic2": "",
                "time_attac_pic": "",
                "timeout1": "0",
                "timeout2": "0",
            }
        ]

    cdata = binascii.hexlify(line)
    ddata = cdata.decode("utf-8").upper()
    edata = hexspace(ddata, 2)
    temp = edata.split("FF 52")
    print(line)
    for i in temp:
        if "7D 4A C0 0A" in i:   #основной таймер
            minutes = int(i.split()[-5], )
            seconds = int(i.split()[-4], )
            milliseconds = int(i.split()[-3], )
            timer_str = (
                f"{minutes}:{seconds:02d}" if minutes != 0 else f"{seconds}.{milliseconds}"
            )
            send_data("TIMER.Text", timer_str)

            # print(i.split()[-7], i)
            # if i.split()[-7] == "13" or i.split()[-7] == "10":
            # new_data[0]["timeGFX"] = timer_str
        elif "7D 4A C0 07" in i:    #Счет
            if i.split()[-7] == "06":   #Счет первой команды
                score1 = int(i.split()[-4], 16)
                # new_data[0]["points1"] = score1
                send_data("Score_Home.Text", score1)
            elif i.split()[-7] == "07":   #Счет второй команды
                score2 = int(i.split()[-4], 16)
                send_data("Score_Away.Text", score2)
                # new_data[0]["points2"] = score2
            else:
                print("[СЧЁТ] == НЕПОНЯТНО")
        elif "7D 4A C0 06" in i:    #Информация
            if i.split()[-6] == "09":   #фолы первой команды
                foul1 = int(i.split()[-3], 16)
                # new_data[0]["foul1"] = foul1
                send_data("fouls1.Source", f"D:\\Графика\\БАСКЕТБОЛ\\ЕДИНАЯ ЛИГА ВТБ 2022-2023\\Scorebug Indicators\\Home_{foul1}.png")
            elif i.split()[-6] == "0A":   #фолы второй команды
                foul2 = int(i.split()[-3], 16)
                send_data("fouls2.Source", f"D:\\Графика\\БАСКЕТБОЛ\\ЕДИНАЯ ЛИГА ВТБ 2022-2023\\Scorebug Indicators\\Away_{foul2}.png")
                # new_data[0]["foul2"] = foul2
            elif i.split()[-6] == "0E": #тайм-аут первой команды
                time_out1 = int(i.split()[-3], 16)
                # new_data[0]["timeout1"] = time_out1
            elif i.split()[-6] == "0F": #тайм-аут второй команды
                time_out2 = int(i.split()[-3], 16)
                # new_data[0]["timeout2"] = time_out2
            elif i.split()[-6] == "08": #четверть
                quarter = int(i.split()[-3], 16)
                # new_data[0]["quarter"] = quarter

        elif "79 84 C0 0A" in i:   #24 секунды
            # print(i)
            seconds = int(i.split()[-4])
            milliseconds = int(i.split()[-3])
            if seconds < int(5):
                time_attack = f"{seconds}.{milliseconds}"
                timer_pic = "D:\\Графика\\БАСКЕТБОЛ\\ЕДИНАЯ ЛИГА ВТБ 2022-2023\\Scorebug Indicators\\24Sec_Red.png"
            else:
                time_attack = seconds
                timer_pic = "D:\\Графика\\БАСКЕТБОЛ\\ЕДИНАЯ ЛИГА ВТБ 2022-2023\\Scorebug Indicators\\24Sec_Empty.png"
            if time_attack == "0.0":
                time_attack = ""
                timer_pic = "D:\\Графика\\БАСКЕТБОЛ\\ЕДИНАЯ ЛИГА ВТБ 2022-2023\\Scorebug Indicators\\24Sec_Empty.png"
            send_data("ATTACK.Text", time_attack)
            send_data("24SECBACKGROUND.Source", timer_pic)

            # print(time_attack)
        elif "89 4E C8 05" in i:
            if i.split()[-3] == "05":   #таймер 24 секунд выключен
                time_attack = ""
                timer_pic = "D:\\Графика\\БАСКЕТБОЛ\\ЕДИНАЯ ЛИГА ВТБ 2022-2023\\Scorebug Indicators\\24Sec_Empty.png"
                send_data("ATTACK.Text", time_attack)
                send_data("24SECBACKGROUND.Source", timer_pic)
    # data = {
    #     "TIMER.Text": timer_str,
    #     "ATTACK.Text": time_attack,
    #     "Score_Home.Text": score1,
    #     "Score_Away.Text": score2,
    #     "fouls1.Source": f"D:\\Графика\\БАСКЕТБОЛ\\ЕДИНАЯ ЛИГА ВТБ 2022-2023\\Scorebug Indicators\\Home_{foul1}.png",
    #     "fouls2.Source": f"D:\\Графика\\БАСКЕТБОЛ\\ЕДИНАЯ ЛИГА ВТБ 2022-2023\\Scorebug Indicators\\Away_{foul2}.png",
    #     "24SECBACKGROUND.Source": timer_pic,
    # }

# 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_Nata_Nport_{current_time}.log"
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s %(levelname)s %(message)s",
        filename=LogFileName,
        filemode="w",
    )

    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)
            parse_new(data)

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


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