import re
from typing import List, Optional

from UniTAP.libs.lib_tsi.tsi_types import TSI_OPF_PARAMETER


def parse_link_training(parameters_list: List[TSI_OPF_PARAMETER]):
    dp_lanes = 0
    dp_link_rate = 0
    encoding = None

    for param in parameters_list:
        if param.name == 'Lane Count':
            dp_lanes, = re.findall(r'\d+', param.description)
        if param.name == 'Link Rate':
            dp_link_rate = re.findall(r'\d+', param.description)
            if len(dp_link_rate) == 0:
                dp_link_rate = 0
            elif len(dp_link_rate) == 2:
                dp_link_rate = f"{dp_link_rate[0]}.{dp_link_rate[1]}"
        if len(parameters_list) >= 3:
            if param.name == 'Encoding':
                encoding = re.findall(r'\d+\w+/\d+\w+', param.description)
                if len(encoding) == 0:
                    encoding = "8b/10b"
                else:
                    encoding = encoding[0]

    return int(dp_lanes), float(dp_link_rate), encoding


def parse_video_mode_2(parameters_list: List[TSI_OPF_PARAMETER]):
    res_x = 0
    res_y = 0
    res_frate = 0
    res_bpc = 0
    tim_std = None
    tim_rb = None

    for param in parameters_list:
        if param.name == 'Video Mode':
            result = re.findall(r'\d+|RB1|RB2|VIC \d+|DMT \w+|CVT \w+', param.description)
            if len(result) == 5:
                res_x, res_y, res_frate, res_bpc, tim_std = result
            else:
                res_x, res_y, res_frate, res_bpc, tim_rb, tim_std = result

    return int(res_x), int(res_y), int(float(res_frate) * 1000), int(res_bpc), tim_std, tim_rb


def parse_video_mode_6(pattern_request: str, parameters_list: List[TSI_OPF_PARAMETER]):
    res_x = 0
    res_y = 0
    res_frate = 0
    res_bpc = 0
    col_format = 0
    col_range = 0
    col_yc = None
    timing_standard = None

    pattern_name = re.findall(r'Color Ramp|Color Square', pattern_request)[0]

    for param in parameters_list:
        if param.name == 'Video Mode':
            result = re.findall(r'\d+|RB1|RB2', param.description)
            if len(result) == 3:
                res_x, res_y, res_frate = result
            else:
                res_x, res_y, res_frate, timing_standard = result
        elif param.name == 'Color Format':
            result = re.findall(r'RGB|YCbCr 4:4:4|YCbCr 4:2:2|YCbCr 4:2:0|Simple 4:2:2|ITU-601|ITU-709|\d+|VESA|CTA',
                                param.description)
            if len(result) == 3:
                col_format, res_bpc, col_range = result
            elif len(result) == 4:
                col_format, col_yc, res_bpc, col_range = result

    return int(res_x), int(res_y), int(float(res_frate) * 1000), int(
        res_bpc), timing_standard, col_format, col_range, col_yc, pattern_name


def parse_video_mode_9(parameters_list: List[TSI_OPF_PARAMETER], pattern_request: Optional[str] = None):
    res_x = 0
    res_y = 0
    res_frate = 0
    res_bpc = 0
    tim_std = None
    pattern_name = None

    if pattern_request is not None:
        pattern_name = re.findall(r'Color Ramp|Color Square', pattern_request)[0]

    for param in parameters_list:
        if param.name == 'Video Mode':
            result = re.findall(r'\d+|RB1|RB2', param.description)
            if len(result) == 4:
                res_x, res_y, res_frate, res_bpc = result
            elif len(result) == 5:
                res_x, res_y, res_frate, tim_std, res_bpc = result

    return int(res_x), int(res_y), int(float(res_frate) * 1000), int(res_bpc), tim_std, pattern_name


def parse_opf_10(parameters_list: List[TSI_OPF_PARAMETER]):
    res_x, res_y, res_frate, res_bpc, timing_standard = [0] * 5

    audio_pattern = ''
    ch_count = 0
    sample_freq = 0
    sample_size = 0
    ch_alloc = 0
    ch_info = []

    for ind, param in enumerate(parameters_list):
        if param.name == 'Video Mode' and param.description != "Video is not required":
            res_x, res_y, res_frate, res_bpc, timing_standard, _ = parse_video_mode_9(parameters_list=parameters_list)
        elif param.name == 'Audio Pattern':
            audio_pattern = param.description
        elif param.name == 'Channel Count':
            ch_count, = re.findall(r'\d+', param.description)
        elif param.name == 'Sample Frequency':
            sample_freq, = re.findall(r'\d+', param.description)
        elif param.name == 'Sample Size':
            sample_size, = re.findall(r'\d+', param.description)
        elif param.name == 'Channel Allocation' and ind == 5:
            ch_alloc = re.findall(r'FL/FR|LFE1|FC|BL/BR|BC|FLC/FRC|RLC/RRC|FLW/FRW|TpFL/TpFR|TpC|TpFC|LS/RS|LFE2|TpBC'
                                  r'|SiL/SiR|TpSiL/TpSiR|TpBL/TpBR|BtFC|BtFL/BtFR|TpLS/TpRS', param.description)
        elif param.name == 'Channel Allocation' and ind > 5:
            ch_info.append(re.findall(r'\d+', param.description)[0])

    return int(res_x), int(res_y), int(res_frate), int(res_bpc), timing_standard, audio_pattern, \
           int(ch_count), int(sample_freq), int(sample_size), ch_alloc, ch_info if len(ch_info) > 0 else None


def parse_message(message: str):
    return [str(message)]


def parse_video_mode_19(parameters_list: List[TSI_OPF_PARAMETER]):
    use_3tap = False
    for param in parameters_list:
        if param.name == 'Conversion type filter':
            use_3tap = param.description.find('3-Tap Filter') != -1
    return [use_3tap]


def parse_video_mode_18(parameters_list: List[TSI_OPF_PARAMETER]):
    res_x = 0
    res_y = 0
    res_frate = 0
    res_bpc = 0
    col_format = 0
    col_range = 0
    col_yc = 0
    tim_std = 0

    for param in parameters_list:
        if param.name == 'Video Mode':
            res_x, res_y, res_frate, tim_std = re.findall(r'\d+|CTA|RB1|RB2', param.description)
        elif param.name == 'Color Format':
            color_format_str = param.description.replace("ITU-709", '')
            col_format, res_bpc, col_range = re.findall(
                r'RGB|YCbCr 4:2:2|YCbCr 4:4:4|YCbCr 4:2:0|Simple 4:2:2|\d+|VESA|CTA', color_format_str)
            col_yc = 'ITU-709' if col_format != 'RGB' else None

    return int(res_x), int(res_y), int(float(res_frate) * 1000), int(res_bpc), col_format, col_range, col_yc, tim_std


def parse_video_mode_20(parameters_list: List[TSI_OPF_PARAMETER], pattern_request: Optional[str] = None):
    pattern_name = None
    res_x = 0
    res_y = 0
    res_frate = 0
    res_bpc = 0
    col_format = 0
    col_range = 0
    col_yc = None
    tim_std = ""
    enable_dsc = False

    if pattern_request is not None:
        if pattern_request.find('DSC compressed') != -1:
            enable_dsc = True
        else:
            pattern_name = re.findall(r'No Video|Color Ramp|Color Square|Black and Vertical lines|Any', pattern_request)[0]
            enable_dsc = False

    for param in parameters_list:
        if param.name == 'Video Mode':
            line = param.description.split("Hz")
            res_x, res_y, res_frate = re.findall(r'\d+', line[0])
            tim_std = re.findall(r'VIC \d+|DMT \w+|UFG \d+|CVT RB\d+|CVT|OVT', line[1])
        elif param.name == 'Color Format':
            color_format_str = param.description
            result = re.findall(r'RGB|YCbCr 4:2:2|YCbCr 4:4:4|YCbCr 4:2:0|Simple 4:2:2|ITU-601|ITU-709|\d+|VESA|CTA',
                                color_format_str)
            if len(result) == 3:
                col_format, res_bpc, col_range = result
            elif len(result) == 4:
                col_format, col_yc, res_bpc, col_range = result

    return int(res_x), int(res_y), int(float(res_frate) * 1000), int(res_bpc), col_format, col_range, col_yc, tim_std,\
           pattern_name, enable_dsc


def parse_opf_21(parameters_list: List[TSI_OPF_PARAMETER]):
    audio_pattern = ''
    ch_count = 0
    sample_freq = 0
    sample_size = 0
    ch_alloc = 0
    ch_info = []

    for ind, param in enumerate(parameters_list):
        if param.name == 'Audio Pattern':
            audio_pattern = param.description
        elif param.name == 'Channel Count':
            ch_count, = re.findall(r'\d+', param.description)
        elif param.name == 'Sample Frequency':
            sample_freq, = re.findall(r'\d+', param.description)
        elif param.name == 'Sample Size':
            sample_size, = re.findall(r'\d+', param.description)
        elif param.name == 'Channel Allocation' and ind == 5:
            ch_alloc = re.findall(r'FL/FR|LFE1|FC|BL/BR|BC|FLC/FRC|RLC/RRC|FLW/FRW|TpFL/TpFR|TpC|TpFC|LS/RS|LFE2|TpBC'
                                  r'|SiL/SiR|TpSiL/TpSiR|TpBL/TpBR|BtFC|BtFL/BtFR|TpLS/TpRS', param.description)
        elif param.name == 'Channel Allocation' and ind > 5:
            ch_info.append(re.findall(r'\d+', param.description)[0])

    return (audio_pattern, int(ch_count), int(sample_freq), int(sample_size), ch_alloc,
            ch_info if len(ch_info) > 0 else None)


def parse_video_mode_103(parameters_list: List[TSI_OPF_PARAMETER]):
    width = 0
    height = 0
    res_frate = 60000
    color_format = ""
    block_prediction = False
    bpc = 8
    bpp = 8
    h_slice_number = 0
    buffer_bit_depth = 8
    v_slice_number = 0
    dsc_v_minor = 1
    dsc_v_major = 1

    for param in parameters_list:
        if param.name == "Video mode":
            width, height, res_frate = re.findall(r'\d+', param.description)
        elif param.name == "Color format":
            color_format = re.findall(r'RGB|YCbCr 4:2:2|YCbCr 4:4:4|YCbCr 4:2:0|Simple 4:2:2', param.description)[0]
        elif param.name == 'Block prediction':
            block_prediction = False if param.description.find("disabled") != -1 else True
        elif param.name == 'Bits per component':
            bpc = re.findall(r'\d+', param.description)[0]
        elif param.name == 'Bits per pixel (1/16 units)':
            bpp = re.findall(r'\d+', param.description)[2]
        elif param.name == 'Horizontal slice number':
            h_slice_number = re.findall(r'\d+', param.description)[0]
        elif param.name == 'Buffer bit depth':
            buffer_bit_depth = re.findall(r'\d+', param.description)[0]
        elif param.name == 'Vertical slice number':
            v_slice_number = re.findall(r'\d+', param.description)[0]
        elif param.name == 'DSC Algorithm revision':
            dsc_v_minor, dsc_v_major = re.findall(r'\d+', param.description)

    return int(width), int(height), int(float(res_frate) * 1000), color_format, block_prediction, int(bpc), int(bpp),\
           int(h_slice_number), int(buffer_bit_depth), int(v_slice_number), int(dsc_v_major), int(dsc_v_minor)


def parse_video_mode_120(parameters_list: List[TSI_OPF_PARAMETER]):
    res_x = 0
    res_y = 0
    res_frate = 0
    res_bpc = 0
    color_format = ""

    for param in parameters_list:
        if param.name == "Video pattern":
            res_x, res_y, res_frate, res_bpc, color_format = re.findall(r'\d+|RGB|YCbCr 4:2:2|YCbCr 4:4:4|YCbCr 4:2:0|Simple 4:2:2|YCbCr422|YCbCr444|YCbCr420|Simple422', param.description)

    return int(res_x), int(res_y), int(float(res_frate) * 1000), int(res_bpc), color_format


def parse_video_mode_140(parameters_list: List[TSI_OPF_PARAMETER]):
    res_x = 0
    res_y = 0
    res_frate = 0
    tim_std = 0
    tim_std_num = None

    for param in parameters_list:
        if param.name == 'Timing':
            result = re.findall(r'\d[a-fA-F]h|\d+|VIC|DMT|RB1|RB2|RB3', param.description)
            if len(result) == 5:
                res_x, res_y, res_frate, tim_std, tim_std_num = result
            elif len(result) == 4:
                res_x, res_y, res_frate, tim_std = result

    return int(res_x), int(res_y), int(float(res_frate) * 1000), tim_std, tim_std_num


def parse_video_mode_141(parameters_list: List[TSI_OPF_PARAMETER]):
    audio_format = ''
    channels = 0
    size = 0
    rate = 0

    for param in parameters_list:
        if param.name == 'Audio':
            audio_format, channels, size, rate = re.findall(r'LPCM|\d+.\d+|\d+', param.description)

    return audio_format, int(channels), int(size), int(float(rate) * 1000)


def parse_video_mode_143(parameters_list: List[TSI_OPF_PARAMETER]):
    res_frate = 0

    for param in parameters_list:
        if param.name == 'Refresh Rate':
            res_frate = re.findall(r'\d+', param.description)[0]

    return [int(float(res_frate))]


def parse_video_mode_144(parameters_list: List[TSI_OPF_PARAMETER]):
    return [parameters_list[0].description]
