import socket
import struct
import ctypes
from Grifo_E_1553lib import mil1553udp
from Grifo_E_1553lib.mil1553udp import UDP1553Header
from Grifo_E_1553lib.messages.msg_rdr_settings_and_parameters import MsgRdrSettingsAndParameters
from Grifo_E_1553lib.messages.msg_rdr_operation_command import MsgRdrOperationCommand
from Grifo_E_1553lib.data_types.enums import TargetHistory, RdrModes

UDP_IP = "127.0.0.1"
UDP_PORT = 61553

def main():
	print(f"Sending to {UDP_IP}:{UDP_PORT}")

	sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

	# Crea un header UDP1553 di esempio
	header = UDP1553Header()
	header.marker1553 = 0x1553
	header.otype = 0x4342  # BC
	packed_header = bytes(header)

	# Crea un messaggio MsgRdrSettingsAndParameters di esempio
	message = MsgRdrSettingsAndParameters()
	message.settings.set_history_level(TargetHistory.TARGET_HISTORY_LEVEL_03)
	# populate date and time from system clock
	from datetime import datetime
	now = datetime.now()
	try:
		message.date_of_mission.set_year_of_mission(now.year - 2000)
		message.date_of_mission.set_month_of_mission(now.month)
		message.date_of_mission.set_day_of_mission(now.day)
	except Exception:
		try:
			from Grifo_E_1553lib.data_types.date_of_mission import DateOfMission
			dm = DateOfMission()
			dm.set_year_of_mission(now.year - 2000)
			dm.set_month_of_mission(now.month)
			dm.set_day_of_mission(now.day)
			setattr(message, 'date_of_mission', dm.raw)
		except Exception:
			pass
	# time: seconds since midnight divided by 2 (LSB = 2s)
	secs = now.hour*3600 + now.minute*60 + now.second
	try:
		message.time_of_mission.set(secs//2)
	except Exception:
		try:
			setattr(message, 'time_of_mission', secs//2)
		except Exception:
			pass
	packed_message = bytes(message)

	# Combina l'header e il messaggio
	try:
		command_word = getattr(message, 'command_word')
	except Exception:
		command_word = 0
	packet = packed_header + struct.pack(">H", command_word) + packed_message

	sock.sendto(packet, (UDP_IP, UDP_PORT))

	print("Message sent!")


if __name__ == '__main__':
	main()