import struct
from datetime import datetime
from Grifo_E_1553lib.messages.msg_rdr_settings_and_parameters import MsgRdrSettingsAndParameters

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 = MsgRdrSettingsAndParameters()
    # date_of_mission may be a ctypes union instance or an int depending on initialization
    # set date/time from system clock similar to sender behavior
    now = datetime.now()
    d = m.date_of_mission
    if hasattr(d, 'raw'):
        print("Before change: date.raw=0x%04X" % d.raw)
        d.set_year_of_mission(now.year - 2000)
        d.set_month_of_mission(now.month)
        d.set_day_of_mission(now.day)
        print("After date set: date.raw=0x%04X" % d.raw)
    else:
        # fallback: write via setting the field to a new DateOfMission object
        from Grifo_E_1553lib.data_types.date_of_mission import DateOfMission
        dm = DateOfMission()
        print("Before change: date.raw=0x%04X" % int(d))
        dm.set_day_of_mission(1)
        # assign the raw uint16 value into the structure field
        setattr(m, 'date_of_mission', dm.raw)
        print("After set_day_of_mission(1): date.raw=0x%04X" % dm.raw)
    # set time_of_mission (lsb = 2 seconds)
    seconds = now.hour * 3600 + now.minute * 60 + now.second
    tval = seconds // 2
    if hasattr(m.time_of_mission, 'set'):
        m.time_of_mission.set(tval)
    else:
        setattr(m, 'time_of_mission', tval)

    le, be = dump_message_words(m)

if __name__ == '__main__':
    main()
