/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */


//
// Instantiate the switch debouncer
//
static eCxx::Debounce8Switch db8sw;


//
// Helper functions
//
static void eCxx_user_init_initPins()
{
    // Initialize the LED pin to input without pull-up mode and read from it
    pinDDX_LED.pinModeInput(false);
    pinDDX_LED.digitalRead();

    // Initialize the LED pin to input with pull-up mode and read from it
    pinDDX_LED.pinModeInput(true);
    pinDDX_LED.digitalRead();

    // Initialize the LED pin to output mode and write to it
    pinDDX_LED.pinModeOutput();
    pinDDX_LED.digitalWrite(true );
    pinDDX_LED.digitalWrite(false);

    // Initialize the switch pin to input with pull-up mode
    pinDDX_SW.pinModeInput(true);
}


static void eCxx_user_task_execute()
{
    // A flag to indicate if the system shall blink the activity indicator LED automatically
    // (with ~200 mS delay as specified by Application_CRTPBase::ActivityIndicatorLEDBlinkDelay)
    static bool autoBlink = true;

    // Process event and delay
    static eCxx::uint32_t prvMillis = 0;
           eCxx::uint32_t curMillis = App::processEvent(autoBlink);
    if(curMillis - prvMillis < 50) return;
    else                           prvMillis = curMillis;

    // Read the switch
    if( pinDDX_SW.digitalRead() ) db8sw.debounce(0b00000000); // The switch is active low
    else                          db8sw.debounce(0b00000001);

    if( db8sw.pressed(0b00000001) ) autoBlink = !autoBlink;

    // Check if there is no need to blink the activity indicator LED manually
    if(autoBlink) return;

    // Blink the activity indicator LED manually (with ~50 mS delay)
    static bool state = false;
    state = !state;

    pinDDX_LED.digitalWrite(state);
}
