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


host = "10.4.100.17"
port = 4420
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}"
    with open(name, "a") as file:
        file.write(message_with_time + "\n")


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


def seconds(data):
    if data.strip() == "":
        return ""
    try:
        return str(int(data))
    except Exception as ex:
        word_to_int = "ABCDEF"
        if data[0] in word_to_int:
            temp = f"{word_to_int.index(data[0])}.{data[1]}"
            return "" if temp == "0.0" else temp if temp != "5.0" else "5"

def parse2(data):
    # print("+", "_".join(data), len(data))
    timer = data[2:7].strip().replace("\x00","").replace('/', '')
    if ":" in timer:
        timer = f'{int(timer.split(":")[0])}:{timer.split(":")[1]}'
    elif '.' in timer:
        timer = f'{int(timer.split(".")[0])}.{timer.split(".")[1]}'
    score1 = data[7:10].strip().replace("\x00","").replace('/', '')
    score2 = data[10:13].strip().replace("\x00","").replace('/', '')
    attack = seconds(data[23:25].strip())
    test = data[20]
    send_data("TIMER.Text", timer)
    send_data("SCORE1.Text", int(score1))
    send_data("SCORE2.Text", int(score2))
    send_data("24sec.Text", attack)
    print(f"_{data}_", timer, int(score1), int(score2), attack)


def read_logs():
    with open(r"C:\Users\soule\Downloads\Telegram Desktop\LOGS\LOGS\timer_MBA_2026-01-04_14-16-13.log", "r", encoding="utf-8") as file:
        for line in file:
            parts = line.strip().split("INFO:root:")
            if len(parts) == 2:
                timestamp = parts[0][1:]
                data = parts[1]

                parse2(data)

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


def main():
    current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    if not os.path.isdir("LOGS"):
        os.mkdir("LOGS")
        
    tcp_socket = socket(AF_INET, SOCK_STREAM)
    tcp_socket.connect(ADDR)
    logger = logging.getLogger(__name__)
    LogFileName = f"LOGS/timer_MBA_{current_time}.log"
    logging.basicConfig(filename=LogFileName, level=logging.INFO)

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

            # print(data)
            logging.info(data)
            parse2(data)
    except KeyboardInterrupt:
        tcp_socket.close()
        sys.exit(1)


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

