from UniTAP.libs.lib_tsi.tsi_io import PortIO
from .types import LinkMode
from UniTAP.libs.lib_tsi.tsi_types import TSI_HDRX_LINK_STATUS_R
from ctypes import c_uint32


class TmdsRx:
    """
    CLass `TmdsRx` allows working with TMDS on Sink (RX - receiver) side.
    - Get link mode `link_mode`.
    - Get clock rate `clock_rate`.
    - Get input stream lock state `input_stream_lock`.
    """
    def __init__(self, port_io: PortIO):
        self.__io = port_io
        self.__link_mode = LinkMode.Unknown
        self.__input_stream_lock = False

    def __read_link_status(self) -> int:
        return self.__io.get(TSI_HDRX_LINK_STATUS_R, c_uint32)[1]

    @property
    def clock_rate(self) -> int:
        """
        Returns current clock rate.

        Returns:
            object of int type
        """
        return 6 if self.__read_link_status() & 0x2 else 3

    @property
    def link_mode(self) -> LinkMode:
        """
        Returns current link mode.

        Returns:
            object of `LinkMode` type
        """
        self.__link_mode = LinkMode(self.__read_link_status() & 0x8)
        return self.__link_mode

    @property
    def input_stream_lock(self) -> bool:
        """
        Returns current state of input stream lock.

        Returns:
            object of bool type
        """
        self.__input_stream_lock = (self.__read_link_status() & 0x4) != 0
        return self.__input_stream_lock

    def __str__(self):
        return f"Clock rate: {self.clock_rate}G\n" \
               f"Link mode: {self.link_mode.name}\n" \
               f"Input stream lock: {'Enable' if self.input_stream_lock else 'Disable'}"
