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


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


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

    if len(edata.split()) == 33:
        temp_data = edata.split()
        temp_new = [int(t, 16) for t in temp_data]
        minutes = temp_new[6]
        seconds = temp_new[7]
        milliseconds = temp_new[8]
        timer_str = (
            f"{minutes}:{seconds:02d}"
            if minutes != 0
            else f"{seconds:02d}.{milliseconds}"
        )
        active_temp = temp_new[
            9
        ]  # 133 - таймер идёт | 132 - таймер стоит | 128 - не игровое время стоит | 129 - не игровое время идёт

        if temp_new[-2] != 0:
            time_attack = (
                temp_new[-4] if temp_new[-4] > 4 else f"{temp_new[-4]}.{temp_new[-3]}"
            )
        else:
            time_attack = ""  # temp_new[-2] == 1 - таймер идёт | 2 - таймер стоит | 0 - таймер не отображён

        # print(f"{str(temp_new):<120}__{timer_str:<7}__{time_attack:<3}__")
    else:
        temp_data = edata.split()
        temp_new = [int(t, 16) for t in temp_data]

    # time.sleep(0.1)


def read_logs():
    with open("timer_NN_2023-12-20_18-17-29.log", "r") as file:
        # with open("timer_NN_test.log", "r") as file:
        temp_line = ""
        for line in file:
            parts = line.strip().split(" DEBUG ")
            if len(parts) == 2:
                timestamp = parts[0][1:]
                data = eval(parts[1])
                parse(data)
                time.sllep(0.1)

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


def parse_2(data):
    data = data.decode()
    print(data)
    if "S04" in data:
        temp = data.split("S04")[1]
        print(f"{data:<50}", temp)
    elif "S09" in data:                 #White
        temp = data
    elif "S00" in data:                 #Red
        temp = data

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_NPORT_zzz_{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)
        temp = b""
        line_new = b""
        while True:
            data = tcp_socket.recv(1024)
            logging.debug(data)
            print(data)
            if b"\x03" in data:
                temp += data
                line_new = temp
                temp = b""
            else:
                temp += data

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


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