#include "hal_dfu.h"
#include "system.h"
#include "ble_dfu.h"
#include "nrf_dfu_ble_svci_bond_sharing.h"
#include "nrf_svci_async_function.h"
#include "nrf_svci_async_handler.h"

#if BLE_DFU_ENANBLE
static void ble_dfu_evt_handler(ble_dfu_buttonless_evt_type_t event)
{
    switch (event)
    {
    case BLE_DFU_EVT_BOOTLOADER_ENTER_PREPARE:
    {
#if DEBUG_DFU_EN
        SEGGER_RTT_printf(0,"Device is preparing to enter bootloader mode.\n");
#endif
        break;
    }

    case BLE_DFU_EVT_BOOTLOADER_ENTER:
// YOUR_JOB: Write app-specific unwritten data to FLASH, control finalization of this
//           by delaying reset by reporting false in app_shutdown_handler
#if DEBUG_DFU_EN
        SEGGER_RTT_printf(0,"Device will enter bootloader mode.\n");
#endif
        break;

    case BLE_DFU_EVT_BOOTLOADER_ENTER_FAILED:
#if DEBUG_DFU_EN
    SEGGER_RTT_printf(0,"Request to enter bootloader mode failed asynchroneously.\n");
#endif
        // YOUR_JOB: Take corrective measures to resolve the issue
        //           like calling APP_ERROR_CHECK to reset the device.
        break;

    case BLE_DFU_EVT_RESPONSE_SEND_ERROR:
#if DEBUG_DFU_EN
        SEGGER_RTT_printf(0,"Request to send a response to client failed.\n");
#endif
        // YOUR_JOB: Take corrective measures to resolve the issue
        //           like calling APP_ERROR_CHECK to reset the device.
        APP_ERROR_CHECK(false);
        break;

    default:
#if DEBUG_DFU_EN
        SEGGER_RTT_printf(0,"Unknown event from ble_dfu_buttonless.\n");
#endif
        break;
    }
}

void hal_dfu_init(void){
	ret_code_t err_code;
	err_code = ble_dfu_buttonless_async_svci_init();
	APP_ERROR_CHECK(err_code);
}
  
void hal_dfu_server_init(void){
	ret_code_t err_code;
	ble_dfu_buttonless_init_t dfus_init = {0}; //DFU
	dfus_init.evt_handler = ble_dfu_evt_handler;
	err_code = ble_dfu_buttonless_init(&dfus_init);
	APP_ERROR_CHECK(err_code);
}

#endif
