/*
 * can_manager.h
 *
 *  Created on: Sep 16, 2025
 *      Author: herli
 */

#ifndef SRC_CAN_LIBS_CAN_MANAGER_H_
#define SRC_CAN_LIBS_CAN_MANAGER_H_

#include "can_schema.h"

extern uint8_t startup;

extern volatile uint8_t EMPF2_BYTES[8];
extern volatile uint8_t s_empf2_pending;


/* Provide your HAL-backed TX function when initializing the manager. */
void can_manager_init(CanTxFn tx_fn);

/* Send all TX messages flagged with send_on_boot==1 (templates first, then symbols). */
void can_manager_boot(void);

/* RX entrypoint: call from your FDCAN Rx FIFO callback. */
void can_manager_on_rx(uint16_t can_id, const uint8_t data[8], uint8_t dlc);

/* TX by ID (packs symbols; starts from tx_template if present). Returns false if ID not found. */
bool can_manager_send(uint16_t can_id);

/* Utility: direct send of a message definition (useful if you already called can_db_find) */
bool can_manager_send_msg(const CanMessageDef *msg);

/* NEW: runtime registration of message handlers (keeps can_db.c pure-data) */
bool can_manager_register_handler(uint16_t can_id, CanDirection dir, CanRxHandler handler);

/* Register a handler for a specific message DEFINITION (no IDs in app code) */
bool can_manager_register_handler_msg(const CanMessageDef *msg, CanRxHandler handler);

// STARTUP MANAGER FUNCTIONS //
void can_manager_set_startup_reply_msg(const CanMessageDef *reply_msg); // use MSG_ID_EMPF3
/* Optional: we expose a ready-made startup-trigger handler you can register. */
void can_manager_rx_startup_trigger(const CanMessageDef *msg, const uint8_t in[8], CanTxFn tx);

void can_manager_rx_boot_reply_always(const CanMessageDef *msg, const uint8_t in[8], CanTxFn tx);

// REQUEST MANAGER FUNCTIONS //
/* Address-request handler (uses EMPF2 as the reply message def) */
void can_manager_set_request_reply_msg(const CanMessageDef *reply_msg);    // use MSG_ID_EMPF2
void can_manager_rx_address_request(const CanMessageDef *msg, const uint8_t in[8], CanTxFn tx);

// Request/Reply control for EMPF2
bool can_manager_empf2_has_pending(void);
void can_manager_empf2_clear_pending(void);

#endif /* SRC_CAN_LIBS_CAN_MANAGER_H_ */
