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


SETTING = "19200,RS-485"
HOST = "192.168.127.254"
PORT = 1993

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


def parse(line):
    if len(line) > 6:
        try:
            timer_bool = 0
            if b"\xf87" in line:
                temp_new = str(line.split(b"\xf87")[1])
            elif b"\xf88" in line:
                temp_new = str(line.split(b"\xf88")[1])
            elif b"\xf83" in line:
                temp_new = str(line.split(b"\xf83")[1])
                timer_bool = 1
            print(line)
            timer_temp = temp_new[4:8]
            # print(str(timer_temp) == '\\xf2')
            if timer_temp != "\\xf2":
                if timer_temp[-1] != " ":
                    minutes = int(timer_temp[:2])
                    seconds = timer_temp[2:]
                    timer_str = f"{minutes}:{seconds}"
                else:
                    seconds = int(timer_temp[0:2])
                    milliseconds = int(timer_temp[2:])
                    timer_str = f"{seconds}.{milliseconds}"
                send_data("TIMER.Text", timer_str)
                if timer_bool == 1:
                    quarter = temp_new[14]
                    points1 = (temp_new[8:11]).strip()
                    points2 = (temp_new[11:14]).strip()
                    fouls1 = temp_new[15]
                    fouls2 = temp_new[16]
                    send_data("SCORE1.Text", points1)
                    send_data("SCORE2.Text", points2)                
                    
                attack_display = temp_new[51:53]
                if attack_display == "30":
                    time_attack = ""
                else:
                    word_to_int = "ABCDEFGHI@"
                    time_attack_temp = temp_new[48:50]
                    # print(time_attack_temp)
                    # print(word_to_int.index(time_attack_temp[1])+1 if time_attack_temp[1] != '@' else '0')
                    if time_attack_temp[1] in word_to_int:
                        time_attack = f"{time_attack_temp[0]}.{word_to_int.index(time_attack_temp[1])+1 if time_attack_temp[1] != '@' else '0'}"
                    else:
                        time_attack = (
                            int(time_attack_temp)
                            if time_attack_temp != "  "
                            else time_attack_temp
                        )
                    if time_attack == "0.0":
                        time_attack = ""
                if timer_str == "0:00":
                    timer_str = "0.0"

                send_data("24sec.Text", time_attack)
        except Exception as ex:
            print(ex)
            pass


def read_logs():
    with open(
        r"C:\Users\soule\Downloads\Telegram Desktop\timer_Megasport_Nport_2024-03-05_20-00-17.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])
                if b"\xf83" in data or b"\xf88" in data or b"\xf87" in data:
                    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_Megasport_Nport_{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)
            logging.debug(data)
            if b"\xf83" in data or b"\xf88" in data or b"\xf87" in data:
                parse(data)
    except KeyboardInterrupt:
        tcp_socket.close()
        sys.exit(1)


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