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


//
// Instantiate the BCMOutput class
//
static eCxx::BCMOutput<3> bcmRGB( eCxx::makeArray<eCxx::uint8_t, BCM_R, BCM_G, BCM_B>() );


//
// Helper functions
//
static void eCxx_user_init_initializeBCMPin()
{
    // Set the RGB LED pins as output and turn them off initially
    App::setPinMode(BCM_R, App::PinMode::Output);
    App::setPinMode(BCM_G, App::PinMode::Output);
    App::setPinMode(BCM_B, App::PinMode::Output);

#if defined(__AVR_ARCH_X__) || defined(__XTENSA__)
    App::digitalWrite(BCM_R, false);
    App::digitalWrite(BCM_G, false);
    App::digitalWrite(BCM_B, false);
#else
    App::digitalWrite(BCM_R, true); // Active low
    App::digitalWrite(BCM_G, true); // Active low
    App::digitalWrite(BCM_B, true); // Active low
#endif
}


static void eCxx_user_task_updateBCMAnimation()
{
    // Process event and delay
    static eCxx::uint32_t prvMillis = 0;
           eCxx::uint32_t curMillis = App::processEvent();
    if(curMillis - prvMillis < 25) return;
    else                           prvMillis = curMillis;

    // Update LED animation
    static uint8_t phase =   2;

    static uint8_t r     = 255;
    static uint8_t g     =   0;
    static uint8_t b     =   0;

    if(phase == 0) {
        if(!r) {
            phase = 1;
        }
        else {
            --r;
            g = 255 - r;
        }
    }
    else if(phase == 1) {
        if(!g) {
            phase = 2;
        }
        else {
            --g;
            b = 255 - g;
        }
    }
    else if(phase == 2) {
        if(!b) {
            phase = 0;
        }
        else {
            --b;
            r = 255 - b;
        }
    }

    // Update the BCM values
#if defined(__AVR_ARCH_X__) || defined(__XTENSA__)
    bcmRGB[0] = r;
    bcmRGB[1] = g;
    bcmRGB[2] = b;
#else
    bcmRGB[0] = 255 - r; // The LED is active low
    bcmRGB[1] = 255 - g; // The LED is active low
    bcmRGB[2] = 255 - b; // The LED is active low
#endif
}
