import serial
from serial import SerialException
import datetime
import binascii
import logging
import time
import json

import re

# Configuration Data (later to be put in Panel2Net.conf)
# SerialPort: Name of RPi serial port receiving the panel data
# SerialPort = "COM1"
SerialPort = "COM2"
# BaudRate: Serial port speed (Baud, Default will be adjusted later)
BaudRate = 19200
# PackageByTime: Time Duration until a package is closed
# and sent off (seconds)
PackageByTime = 0.1
# PackageByLength*	Length (in bytes) of data input
# until a package is closed and sent off
PackageByLength = 128
# PackageByLength = 256    попробовать нужно !!!!!!!!!!!!!!!!!!!!
# PackageByLength = 80

# MaxBuffer before flushing (in order to avoid buffer overflow)
BufferMax = 2000


# LogFileName: Name of LogFile
current_time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
LogFileName = f"timer_megasport5_{current_time}.log"
# LogFileSize Maximum Size of LogFile (in Mbytes)
LogFileSize = 10
# LogLevel	Minimum Severity Level to be logged (see severity in Logs)
LogLevel = "E"

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s %(levelname)s %(message)s",
    filename=LogFileName,
    filemode="w",
)

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

ser = serial.Serial()
ser.port = SerialPort
ser.baudrate = BaudRate
ser.bytesize = serial.EIGHTBITS
# number of bits per bytes
ser.parity = serial.PARITY_NONE
# set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE
# number of stop bits
ser.timeout = PackageByTime
# non-block read
ser.xonxoff = False
# disable software flow control
ser.rtscts = False
# disable hardware (RTS/CTS) flow control
ser.dsrdtr = False
# disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2
# timeout for write

PATH = (
    r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\python\JSON\timer_basketball.json"
)
new_data = {
    "timeGFX": "0.0",
    "time_attackGFX": "",
    "quarter": "0",
    "points1": "0",
    "points2": "0",
    "foul1": "0",
    "foul2": "0",
    "foul_pic1": "",
    "foul_pic2": "",
    "time_attac_pic": "",
}
with open(PATH, "w", encoding="utf-8") as file:
    json.dump([new_data], file, ensure_ascii=False, indent=4)


while True:
    try:
        print("Initializing")
        ser.close()
        ser.open()
        if ser.is_open:
            try:
                ser.reset_input_buffer()
                # flush input buffer, discarding all its contents
                ser.reset_output_buffer()
                # flush output buffer, aborting current output
                # and discard all that is in buffer
                RequestCount = 0
                print("Port Opening")
                # Initialise RetryCounter
                RetryCount = 0
                # Initialise Variable to take remainder string
                remainder_hex = b""

                while True:
                    # Read from Serial Interface
                    response = ser.read(PackageByLength)
                    # print(response)
                    if len(response) > 0:
                        # In case there is something coming down the serial path
                        logging.debug(response)

                        if response != b"":
                            data = response
                            # debug line
                            # f.write(data)
                            # f.write("\n")
                            
                            cdata = binascii.hexlify(data)
                            ddata = cdata.decode('utf-8')
                            ddata = ddata.upper()
                            print (ddata)
                            edata = hexspace(ddata, 2)
                            print (edata)
                            
                            
                            
                            # points1 = ""
                            # points2 = ""
                            # quarter = ""
                            # data_str = response.decode(
                            #     "ascii", errors="ignore"
                            # ).replace("\r", "|")
                            # if len(data_str) == 53:
                            #     pattern = r"^(3 0|7  |8  |69i553 |69i557 |69i558 |5:i553 )(.{4})"
                            #     matches = re.findall(pattern, data_str)
                            #     for match in matches:
                            #         found_value = match[0]
                            #         timer_str = match[1]
                            #         if match[0] == "3 0":
                            #             points1 = data_str[7:10].strip()
                            #             points2 = data_str[10:13].strip()
                            #             quarter = data_str[13:14].strip()

                            #         # print(f"Следующие 4 символа: {timer_str}, Найдено: {found_value}, {data_str}_____")
                            # else:
                            #     pattern = r"(\|3 0|\|7  |\|8  |\|69i553 |\|69i557 |\|69i558 |\|5:i553 )(.{4})"
                            #     matches = re.findall(pattern, data_str)
                            #     # print(data_str)
                            #     for match in matches:
                            #         found_value = match[0]
                            #         timer_str = match[1]
                            #         if match[0] == "3 0":
                            #             points1 = data_str[7:10].strip()
                            #             points2 = data_str[10:13].strip()
                            #             quarter = data_str[13:14].strip()

                            #         # print(f"Следующие 4 символа: {timer_str}, Найдено: {found_value}, {data_str}_____")
                            # pattern_attack = r"(.{5})\|"
                            # matches_attack = re.findall(pattern_attack, data_str)
                            # path_pic = r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\Scorebug Indicators"
                            # try:
                            #     if matches_attack[0][2:] == "030":
                            #         time_attackGFX = ""
                            #         time_attac_pic = path_pic + "\\24Sec_empty.png"
                            #     else:
                            #         hex_dict = {
                            #             "I": 9,
                            #             "H": 8,
                            #             "G": 7,
                            #             "F": 6,
                            #             "E": 5,
                            #             "D": 4,
                            #             "C": 3,
                            #             "B": 2,
                            #             "A": 1,
                            #         }
                            #         time_attackGFX = matches_attack[0][:2]
                            #         if time_attackGFX[-1] in [
                            #             "A",
                            #             "B",
                            #             "C",
                            #             "D",
                            #             "E",
                            #             "F",
                            #             "G",
                            #             "H",
                            #             "I",
                            #         ]:
                            #             first_character = time_attackGFX[0]
                            #             second_character = time_attackGFX[1]
                            #             time_attackGFX = str(
                            #                 int(first_character, 16)
                            #                 + hex_dict.get(second_character, 0) / 10.0
                            #             )
                            #             time_attac_pic = path_pic + "\\24Sec_Red.png"
                            #         else:
                            #             time_attac_pic = path_pic + "\\24Sec_Orange.png"
                            # except IndexError:
                            #     pass

                            # if timer_str[0] == " ":
                            #     if timer_str == " 000":
                            #         timer = "0.0"
                            #     else:
                            #         minites = timer_str[:2]
                            #         seconds = timer_str[2:]
                            #         timer = f"{int(minites)}:{seconds}".strip()
                            # elif timer_str[-1] == " ":
                            #     seconds = timer_str[:2]
                            #     milliseconds = timer_str[2:]
                            #     timer = f"{int(seconds)}.{milliseconds}".strip()
                            # else:
                            #     minites = timer_str[:2]
                            #     seconds = timer_str[2:]
                            #     timer = f"{int(minites)}:{seconds}".strip()

                            # print(
                            #     f"Следующие 4 символа: {timer_str}, {timer}, {time_attackGFX}, Найдено: {found_value}, {data_str}_____"
                            # )

                            # with open(PATH, "r", encoding="utf-8") as f:
                            #     new_data = json.load(f)
                            # new_data = new_data[0]
                            # new_data["timeGFX"] = timer
                            # new_data["time_attackGFX"] = time_attackGFX
                            # new_data["time_attac_pic"] = time_attac_pic
                            # if points1:
                            #     new_data["points1"] = points1
                            #     new_data["points2"] = points2
                            #     new_data["quarter"] = quarter
                            # try:
                            #     with open(PATH, "w", encoding="utf-8") as file:
                            #         json.dump(
                            #             [new_data], file, ensure_ascii=False, indent=4
                            #         )
                            # except Exception:
                            #     pass

                    else:
                        # In case nothing is coming down the serial interface
                        print(
                            "\rWaiting for serial input...",
                            end="          ",
                            flush=True,
                        )

            # in case that the Serial Read or HTTP request fails
            except Exception as e1:
                print("error communicating...: " + str(e1))
                logging.error("error communicating...: " + str(e1))

        else:
            print("Port Opening Failed... trying again in 5 seconds")
            time.sleep(0.1)
            ser.close()

    except SerialException:
        print("No port connected... trying again in 5 seconds")
        time.sleep(0.1)
