import struct

from eive_tmtc.pus_tm.defs import PrintWrapper
from tmtccmd.util.tmtc_printer import FsfwTmTcPrinter
from eive_tmtc.pus_tc.devs.plpcdu import SetId


ADC_CHANNELS_NAMED = [
    "U BAT DIV 6",
    "U NEG V FB",
    "I HPA",
    "U HPA DIV 6",
    "I MPA",
    "U MPA DIV 6",
    "I TX",
    "U TX DIV 6",
    "I X8",
    "U X8 DIV 6",
    "I DRO",
    "U DRO DIV 6",
]


def handle_plpcdu_hk(printer: FsfwTmTcPrinter, set_id: int, hk_data: bytes):
    if set_id == SetId.ADC:
        pw = PrintWrapper(printer)
        current_idx = 0
        pw.dlog("Received PL PCDU ADC HK data")
        channels = []
        ch_print = "Channels Raw (hex): ["
        for i in range(12):
            channels.append(
                struct.unpack("!H", hk_data[current_idx : current_idx + 2])[0]
            )
            if i < 11:
                ch_print += f"{channels[i]:06x},"
            else:
                ch_print += f"{channels[i]:06x}]"
            current_idx += 2
        processed_vals = []
        for i in range(12):
            processed_vals.append(
                struct.unpack("!f", hk_data[current_idx : current_idx + 4])[0]
            )
            current_idx += 4
        temp = struct.unpack("!f", hk_data[current_idx : current_idx + 4])[0]
        current_idx += 4
        pw.dlog(f"Temperature: {temp} C")
        pw.dlog(ch_print)
        for i in range(12):
            pw.dlog(f"{ADC_CHANNELS_NAMED[i].ljust(24)} | {processed_vals[i]}")
        printer.print_validity_buffer(validity_buffer=hk_data[current_idx:], num_vars=3)