#include "band_nctu.h"
#include "error.h"
#include "nrf_log.h"
#include "nrfx_wdt.h"
#include "wdt.h"

static bool _gWdtInitialized = false;
static nrfx_wdt_channel_id _gWdtChannelID;

void _wdtReboot(void) {
    NVIC_SystemReset();
}

/*
 *  WDT events handler.
 */
static void _wdtEventHandler(void) {
    NRF_LOG_WARNING("Watchdog timer event handler\n");
    _wdtReboot();
}

int wdtInit(void) {
    ret_code_t errCode;
    nrfx_wdt_config_t wdtConfig = NRFX_WDT_DEAFULT_CONFIG;
	errCode = nrfx_wdt_init(&wdtConfig, _wdtEventHandler);
    if (errCode != NRF_SUCCESS) {
	    NRF_LOG_WARNING("nrfx_wdt_init() failed\n");
        return ERROR_WDT_INITIALIZE_FAIL;
    }
    
	errCode = nrfx_wdt_channel_alloc(&_gWdtChannelID);
	if (errCode != NRF_SUCCESS) {
	    NRF_LOG_WARNING("nrfx_wdt_init() failed\n");
        return ERROR_WDT_INITIALIZE_FAIL;
    }

	nrfx_wdt_enable();

    _gWdtInitialized = true;

    NRF_LOG_WARNING("nrfx_wdt_init() return 0\n");
    return 0;
}

int wdtFeed(void) {
    if (!_gWdtInitialized) {
        return ERROR_WDT_UNINITIALIZED;
    }

    NRF_LOG_DEBUG("Watchdog timer feed\n");
    nrfx_wdt_channel_feed(_gWdtChannelID);

    return 0;
}
