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


HOST = "192.168.127.254"
PORT = 1993

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


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


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 send_data_CW(name, value):
    try:
        with socket(AF_INET, SOCK_STREAM) as tcp_socket:
            tcp_socket.connect(('localhost', 5115))
            data = f"{name}={value}\n".encode()
            # print(f"Sending: {data}")  # Отладка
            tcp_socket.sendall(data)
            # print("Data sent!")  # Подтверждение отправки
    except Exception as e:
        print(f"Error sending TCP data: {e}")




def parse_new(line):
    if line == b"\xff":
        return

    cdata = binascii.hexlify(line)
    ddata = cdata.decode("utf-8").upper()
    edata = hexspace(ddata, 2)
    temp = edata.split("FF 52")
    for i in temp:
        minutes = int(i.split()[5], 16)
        seconds = int(i.split()[6], 16)
        if seconds < 60:
            timer_str = f"{minutes}:{seconds:02d}"
        else:
            timer_str = f"{minutes}.{seconds-128}"
        seconds_24 = int(i.split()[7], 16)
        timer_attack = ""
        timer_pic = "D:\YandexDisk\Графика\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\Scorebug Indicators\\24Sec_Orange.png"
        if seconds_24 == 255:
            timer_attack = ""
        else:
            if seconds_24 > 127:
                seconds_24 = seconds_24 - 128
                timer_attack = f"{seconds_24//10}.{seconds_24%10}"
                timer_pic = "D:\YandexDisk\Графика\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\Scorebug Indicators\\24Sec_Red.png"
            else:
                timer_attack = seconds_24

        quarter = int(i.split()[14][1], 16)
        timeout1 = int(i.split()[10], 16)
        timeout2 = int(i.split()[11], 16)
        score1 = int(i.split()[8], 16)
        score2 = int(i.split()[9], 16)
        foul1 = int(i.split()[12], 16)
        foul2 = int(i.split()[13], 16)
        data = {
            "TIMER": timer_str,
            "ATTACK": timer_attack,
            "Score_Home": score1,
            "Score_Away": score2,
            "fouls1": foul1,
            "fouls2": foul2,
            "quarter": quarter,
        }
        # with open("D:\FIBA CW\\timer.json", "w", encoding="utf-8") as file:
        #     json.dump([data], file, ensure_ascii=False, indent=4)
        send_data_CW("TIMER", data["TIMER"])
        send_data_CW("ATTACK", data["ATTACK"])
        send_data_CW("Score_Home", data["Score_Home"])
        send_data_CW("Score_Away", data["Score_Away"])
        send_data_CW("fouls1", data["fouls1"])
        send_data_CW("fouls2", data["fouls2"])
        send_data_CW("quarter", data["quarter"])
        # send_data("Score_Home", data["Score_Home"])
        # send_data("Score_Away", data["Score_Away"])
        # send_data("fouls1", data["fouls1"])
        # send_data("fouls2", data["fouls2"])
        # send_data("24SECBACKGROUND.Source", data["24SECBACKGROUND.Source"])
        # x = [int(x, 16) for x in i.split()]
        print(f"{i}, {data}")


def read_logs():
    with open(
        r"C:\Code\timer\LOGS\timer_SARATOV copy 2.log",
        "r",
    ) as file:
        for line in file:
            parts = line.strip().split(" DEBUG ")
            if len(parts) == 2:
                timestamp = parts[0]
                data = eval(parts[1])
                parse_new(data)
                time.sleep(0.1)


def main():
    if not os.path.isdir("LOGS"):
        os.mkdir("LOGS")

    LogFileName = f"LOGS/timer_SARATOV copy.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)
            try:
                parse_new(data)
            except Exception as ex:
                print(f"\n{ex}\n")
    except KeyboardInterrupt:
        tcp_socket.close()
        sys.exit(1)


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