import time
from UniTAP.libs.lib_tsi.tsi_io import DeviceIO
from UniTAP.libs.lib_tsi.tsi import TSI_TERMINAL_RW
from ctypes import c_char


class Terminal:

    def __init__(self, device_io: DeviceIO):
        self.__io = device_io

    def write_vr(self, register: int, value: int):
        self.__execute(f"vw {hex(register)} {value}")

    def read_vr(self, register: int) -> str:
        self.__execute(f"vr {hex(register)}")
        return self.__get_logs()

    def write_fifo_vr(self, register: int, value: int):
        self.__execute(f"vfw {hex(register)} {value}")

    def read_fifo_vr(self, register: int) -> str:
        self.__execute(f"vfr {hex(register)}")
        return self.__get_logs()

    def run_command(self, command: str) -> str:
        self.__execute(command)
        return self.__get_logs()

    def __execute(self, command):
        command += '\r'
        str_len = (len(command) / 4 + (1 if len(command) % 4 else 0)) * 4
        self.__io.set(config_id=TSI_TERMINAL_RW,
                      data=command,
                      data_type=c_char,
                      data_count=len(command),
                      data_size=int(str_len))

    def __get_logs(self, timeout: int = 5) -> str:
        try:
            start = time.time()
            result = []
            while time.time() - start < timeout:
                result = self.__io.get(TSI_TERMINAL_RW, c_char, 1024)[1]
                if result[0] != b'\x00':
                    break

            output = ""
            for i in result:
                if i != b'\x00':
                    output += i.decode()

            if output == "":
                print("No output message")
            return output
        except BaseException:
            print("No output message")
            return ""
