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


//
// Instantiate the MAX72XX 7-segment driver
//
static eCxx::MAX72XXSevenSegmentDriver max72xx;


//
// Byte buffer for the digits
//
static constexpr eCxx::uint8_t NUM_MOD = 2;

static eCxx::uint8_t byteBuffer[NUM_MOD * 8];


//
// Helper functions
//
static void eCxx_user_init_MAX72XXSevSeg_and_test()
{
    // Initialize the driver
    max72xx.begin(PIN_DATA, PIN_CLOCK, PIN_LATCH, NUM_MOD, byteBuffer);

    max72xx.setIntensity(eCxx::MAX72XXSevenSegmentDriver::DefIntensity / 2);

    // Perform initial test
    max72xx.setDigit( 0, '0'      );
    max72xx.setDigit( 1, '1'      );
    max72xx.setDigit( 2, '2'      );
    max72xx.setDigit( 3, '3'      );
    max72xx.setDigit( 4, '4'      );
    max72xx.setDigit( 5, '5'      );
    max72xx.setDigit( 6, '6'      );
    max72xx.setDigit( 7, '7'      );
    max72xx.setDigit( 8, '8'      );
    max72xx.setDigit( 9, '9'      );
    max72xx.setDigit(10, 'a'      );
    max72xx.setDigit(11, 'b'      );
    max72xx.setDigit(12, 'c'      );
    max72xx.setDigit(13, 'd'      );
    max72xx.setDigit(14, 'e'      );
    max72xx.setDigit(15, 'f'      );
    max72xx.update  (             );
    App::delayMS(3000);

    max72xx.setDigit( 0, '0'      );
    max72xx.setDigit( 1, '1'      );
    max72xx.setDigit( 2, '2'      );
    max72xx.setDigit( 3, '3', true);
    max72xx.setDigit( 4, '4'      );
    max72xx.setDigit( 5, '5'      );
    max72xx.setDigit( 6, '6', true);
    max72xx.setDigit( 7, '7'      );
    max72xx.setDigit( 8, '8'      );
    max72xx.setDigit( 9, '9'      );
    max72xx.setDigit(10, ' '      );
    max72xx.setDigit(11, '-'      );
    max72xx.setDigit(12, 'E'      );
    max72xx.setDigit(13, 'H'      );
    max72xx.setDigit(14, 'L'      );
    max72xx.setDigit(15, 'P'      );
    max72xx.update  (             );
    App::delayMS(3000);

    max72xx.clearAllDigits();
}


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

    // Update the digits
    static uint8_t digits[NUM_MOD * 8] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    for(eCxx::int8_t i = sizeof(digits) - 1; i >= 0; --i) {
        ++digits[i];
        if(digits[i] < 10) break;
        digits[i] = 0;
    }

    // Update the 7-segment counter
    for(eCxx::uint8_t i = 0; i < sizeof(digits); ++i) {
        max72xx.setDigit(i, digits[i] + '0');
    }

    max72xx.update();
}
