from socket import *
from datetime import datetime
import json
import time

HOST = "10.0.0.57"  # local
PORT = 50002
ADDR = (HOST,PORT)

PATH = "D:\\timer.json"


def connect():
    tcp_socket = socket(AF_INET, SOCK_STREAM)
    tcp_socket.connect(ADDR)
    data = "Hello, world"
    data = str.encode(data)
    tcp_socket.send(data)
    data = bytes.decode(data)
    data = tcp_socket.recv(1024)
    # tcp_socket.close()

    return data


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


def formatted_data(data):
    save_log("logs_mba.txt", data)

    # data_converted = list(data)
    # data_formatted = [
    #     str(hex_value // 16) + str(hex_value % 16) for hex_value in data_converted
    # ]
    # save_log("logs_mba_formatted.txt", data_formatted)


def parse(data_formatted):
    # print(len(data_formatted))
    # print(data_formatted)
    with open(PATH, "r", encoding="utf-8") as f:
        new_data = json.load(f)
    new_data = new_data[0]

    if len(data_formatted) > 30:
        if data_formatted[17] == "010":
            if data_formatted[-8] in ["01", "05"]:
                timer_str = (
                    f"{int(data_formatted[-7])}:{data_formatted[-6]}"
                    if int(data_formatted[-7]) != 0
                    else f"{int(data_formatted[-6])}.{int(data_formatted[-5])}"
                )
                new_data["timeGFX"] = timer_str
                new_data["minutesGFX"] = int(
                    data_formatted[-7]
                )  # [25]  #data_formatted[17] = 010 - таймер      data_formatted[-8] = 05 - овертайм, 06 - перерыв между основным временем и овертаймом, 01 - игровое время, 02 - перерыв между периодами
                new_data["secondsGFX"] = data_formatted[-6]  # [26]
            else:
                timer_str = f"{int(data_formatted[-7])}:{data_formatted[-6]}"
                new_data["timeNotGame"] = timer_str

        if len(data_formatted) == 58:
            new_data[
                "timeDel1"
            ] = f"{int(data_formatted[26])}:{data_formatted[27]}"  # data_formatted[17] = 24 - удаление
            new_data["timeDel2"] = f"{int(data_formatted[41])}:{data_formatted[42]}"

    try:
        with open(PATH, "w", encoding="utf-8") as file:
            json.dump([new_data], file, ensure_ascii=False, indent=4)
        print(new_data)
    except Exception:
        pass


def main():
    with socket(AF_INET, SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        s.sendall(b"Hello, world")
        data = s.recv(1024)
        while True:
            print(data)
            data_new = formatted_data(data)
            time.sleep(.1)
            # parse(data)
            

        


def read_logs():
    import time
    with open("test_logs_balashikha_new.txt", "r") as file:
        for line in file:
            parts = line.strip().split("] ")
            if len(parts) == 2:
                timestamp = parts[0][1:]
                data = parts[1]
                parse(eval(data))
                if len(eval(data)) > 30 and eval(data)[-7] == "00":
                    time.sleep(.1)
                else:
                    time.sleep(1)


if __name__ == "__main__":
    new_data = {
        "timeGFX": "0:00",
        "minutesGFX": "0",
        "secondsGFX": "0",
        "foul1": "0",
        "foul2": "0",
        "quarter": "0",
    }
    with open(PATH, "w", encoding="utf-8") as file:
        json.dump([new_data], file, ensure_ascii=False, indent=4)
    main()
    # read_logs()
