import struct
from Grifo_E_1553lib.messages.msg_rdr_operation_command import MsgRdrOperationCommand
from Grifo_E_1553lib.data_types.rdr_mode_command import RdrModeCommandWord


def dump_message_words(msg):
    b = bytes(msg)
    nwords = len(b)//2
    le = struct.unpack("<%dH" % nwords, b)
    be = struct.unpack(">%dH" % nwords, b)
    print(f"msg len={len(b)} bytes, words={nwords}")
    print("LE words:", [hex(x) for x in le])
    print("BE words:", [hex(x) for x in be])
    return le, be


def main():
    m = MsgRdrOperationCommand()
    # create an explicit RdrModeCommandWord instance and assign it
    rm = RdrModeCommandWord()
    rm.raw = 0

    # Compose raw word according to bit positions (MSB=15..LSB=0):
    # master_mode[15:12]=0xA, des_ctrl[11:9]=0x5, ibit[8]=1, stby[7]=0,
    # freeze[6]=1, stop_powerup[5]=0, reserved11[4]=1, silence[3]=0,
    # sar_type[2]=1, spare[1:0]=2
    master_mode = 0xA
    des_ctrl = 0x5
    ibit = 1
    stby = 0
    freeze = 1
    stop_powerup = 0
    reserved11 = 1
    silence = 0
    sar_type = 1
    spare = 2

    raw = ((master_mode & 0x0F) << 12) | ((des_ctrl & 0x07) << 9) | ((ibit & 0x01) << 8) \
        | ((stby & 0x01) << 7) | ((freeze & 0x01) << 6) | ((stop_powerup & 0x01) << 5) \
        | ((reserved11 & 0x01) << 4) | ((silence & 0x01) << 3) | ((sar_type & 0x01) << 2) \
        | (spare & 0x03)

    rm.raw = raw
    m.rdr_mode_command = rm

    dump_message_words(m)


if __name__ == '__main__':
    main()
