#pragma once
#include "mcp2521_addresses.hpp"
#include "mcp2521_hardware_handle.hpp"

#include <stdint.h>

enum MCP2521_RX_BUFFER {
    RXB0 = 0,
    RXB1 = 1
};

enum MCP2521_TX_BUFFER {
    TXB0 = 0,
    TXB1 = 1,
    TXB2 = 2
};

enum MCP2521_BUFFER_TYPE {
    ID = 0,
    DATA = 1
};

enum MCP2521_OPERATION_MODE {
    NORMAL      = 0b000,
    SLEEP       = 0b001,
    LOOPBACK    = 0b010,
    LISTEN_ONLY = 0b011,
    CONFIG      = 0b100
};

struct rx_info {
    bool extended;

    uint16_t id;
    uint32_t extended_id;

    bool rtr;
    bool extended_rtr;

    uint8_t length;
};

class MCP2521_CommandInterface {
private:
    I_MCP2521_HardwareHandle * hardware_handle;

    intHandlerFunction_t rx0_handler;
    intHandlerFunction_t rx1_handler;
    intHandlerFunction_t tx0_handler;
    intHandlerFunction_t tx1_handler;
    intHandlerFunction_t tx2_handler;
    intHandlerFunction_t error_handler;
    intHandlerFunction_t wakeup_handler;
    intHandlerFunction_t message_error_handler;

    void * rx0_handler_arg;
    void * rx1_handler_arg;
    void * tx0_handler_arg;
    void * tx1_handler_arg;
    void * tx2_handler_arg;
    void * error_handler_arg;
    void * wakeup_handler_arg;
    void * message_error_handler_arg;
public:

    MCP2521_CommandInterface(
        I_MCP2521_HardwareHandle * hardware_handle
    );

    void handleInterrupt();
    
    void reset();
    
    void read_reg(uint8_t address, uint8_t *data, size_t length);
    uint8_t read_reg(uint8_t address);

    void read_rx_buf(MCP2521_RX_BUFFER buffer, MCP2521_BUFFER_TYPE type, uint8_t *data, size_t length);
    
    void write_reg(uint8_t address, uint8_t *data, size_t length);
    void write_reg(uint8_t address, uint8_t data);

    void write_tx_buf(MCP2521_TX_BUFFER buffer, MCP2521_BUFFER_TYPE type, uint8_t *data, size_t length);

    void request_to_send(bool txb2, bool txb1, bool txb0);
    void request_to_send(MCP2521_TX_BUFFER buffer);

    uint8_t read_status();
    uint8_t read_rx_status();

    void bit_modify(uint8_t address, uint8_t mask, uint8_t data);

    // Registering Handlers for Interrupts
    void register_rx0_handler(intHandlerFunction_t handler, void * arg);
    void register_rx1_handler(intHandlerFunction_t handler, void * arg);
    void register_tx0_handler(intHandlerFunction_t handler, void * arg);
    void register_tx1_handler(intHandlerFunction_t handler, void * arg);
    void register_tx2_handler(intHandlerFunction_t handler, void * arg);
    void register_error_handler(intHandlerFunction_t handler, void * arg);
    void register_wakeup_handler(intHandlerFunction_t handler, void * arg);
    void register_message_error_handler(intHandlerFunction_t handler, void * arg);
};

