/*
 * Copyright 2024 NXP
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */
#include "afci_notification.h"
#include "fsl_ctimer.h"
#include "board.h"

#define LED_GPIO GPIO
#define LED_PORT 1
#define LED_PIN  7

#define CTIMER CTIMER1
#define CTIMER_CLK_FREQ CLOCK_GetCTimerClkFreq(1)

#define BLINK_INTERVAL_MS 1000

volatile bool isBlinking = false;
volatile bool isInit = false;
volatile uint32_t blinkCounter = 0;
volatile uint32_t blinkDuration = 0;

void CTIMER1_IRQHandler(void)
{
    CTIMER_ClearStatusFlags(CTIMER, kCTIMER_Match0Flag);

    if (isBlinking) {
        LED_BLUE_TOGGLE();
        blinkCounter += BLINK_INTERVAL_MS;
        
        if (blinkCounter >= blinkDuration) {
            isBlinking = false;
            CTIMER_StopTimer(CTIMER);
        }
    }
}

static void initTimer(void)
{
    /* Match Configuration for Channel 0 */
    ctimer_match_config_t matchConfig0;

    ctimer_config_t timerConfig;
    CTIMER_GetDefaultConfig(&timerConfig);

    CTIMER_Init(CTIMER, &timerConfig);

    /* Configuration 0 */
    matchConfig0.enableCounterReset = true;
    matchConfig0.enableCounterStop  = false;
    matchConfig0.matchValue         = CTIMER_CLK_FREQ / 1000 * BLINK_INTERVAL_MS;
    matchConfig0.outControl         = kCTIMER_Output_NoAction;
    matchConfig0.outPinInitState    = false;
    matchConfig0.enableInterrupt    = true;

    CTIMER_SetupMatch(CTIMER, kCTIMER_Match_0, &matchConfig0);
}

static void start_async_led_blink(uint32_t duration_ms)
{
    if (!isInit) {
        initTimer();
        isInit = true;
    }
    
    if (!isBlinking) {
        isBlinking = true;
        blinkCounter = 0;
        blinkDuration = duration_ms;
        CTIMER_StartTimer(CTIMER);
    }
}

void arc_detected_notify(void* notification)
{
    start_async_led_blink(2000);
}

void arc_cleared_notify(void* notification)
{
    ;
}