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

HOST = "192.168.0.7"
PORT = 40004
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 timer(line):
    temp_new = [int(t, 16) for t in line.split()]
    minutes = temp_new[4]
    seconds = temp_new[5]
    milliseconds = temp_new[6]
    timer_str = (
        f"{minutes}:{seconds:02d}" if minutes != 0 else f"{seconds}.{milliseconds}"
    )
    return timer_str


def attack_time(line):
    temp_new = [int(t, 16) for t in line.split()]
    path_pic = r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\Scorebug Indicators"
    if temp_new[7] != 2:
        seconds = temp_new[5]
        milliseconds = temp_new[6]
        if int(seconds) > 4:
            if int(milliseconds) >= 5:
                seconds = int(seconds) + 1
            else:
                seconds = seconds
            time_attack = seconds
        else:
            time_attack = f"{seconds}.{milliseconds}"
        if time_attack == "0.0":
            time_attack = ""
        # time_attack = (
        #     temp_new[5]
        #     if temp_new[5] > 4
        #     else f"{temp_new[5]}.{temp_new[6]}"
        #     if f"{temp_new[5]}.{temp_new[6]}" != "0.0"
        #     else ""
        # )
        path_pic = path_pic + (
            "\\24Sec_Orange.png"
            if temp_new[5] > 4
            else (
                "\\24Sec_Red.png"
                if f"{temp_new[5]}.{temp_new[6]}" != "0.0"
                else "\\24Sec_empty.png"
            )
        )
    else:
        time_attack = ""  # temp_new[-2] == 1 - таймер идёт | 2 - таймер стоит | 0 - таймер не отображён
        path_pic = path_pic + "\\24Sec_empty.png"
    return time_attack, path_pic

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": 41,
        "Input": "SCOREBUG",
        "SelectedName": name,
        "Value": value,
    }
    session.get(url, params=params)

def parse(line):
    cdata = binascii.hexlify(line)
    ddata = cdata.decode("utf-8").upper()
    edata = hexspace(ddata, 2)

    temp_line = ""
    line = ""
    if len(edata.split()) in [2, 31, 32, 1]:
        if temp_line == "":
            temp_line = edata
        else:
            line = temp_line + edata
            temp_line = ""
    else:
        line = edata

    data = line.split("FE FF")
    path_pic_foul = (
        r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\Scorebug Indicators"
    )
    diff1, diff2 = 0, 0
    for d in data:
        if d != "":
            temp_d = d.strip()
            if "08 01" in temp_d[:5] and str(temp_d.split()[-2])[0] == "8":
                timer_str = timer(temp_d)
                send_data("TIMER.Text", timer_str)
                aaaaa = temp_d.split()[-2]
            elif "08 03" in temp_d[:5]:
                time_attack, path_pic = attack_time(temp_d)
                send_data("24sec.Text", time_attack)
                aaaa = temp_d.split()[-2], int(temp_d.split()[-2], 16)
            elif "0D 1F" in temp_d[:5]:
                send_data("SCORE1.Text", int(temp_d.split()[2], 16))
                send_data("SCORE2.Text", int(temp_d.split()[3], 16))
                

def read_logs():

    score1, score2 = 0, 0
    with open("timer_NN_1.log", "r") as file:
        # with open("timer_NN_test.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])
                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_NN_{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)
            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)
