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


//
// User defined characters
//
static const eCxx::uint8_t PROGMEM userChars[8][8] = {
   { 0x1B, 0x11, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00 },
   { 0x11, 0x1B, 0x11, 0x0A, 0x00, 0x00, 0x00, 0x00 },
   { 0x0A, 0x11, 0x1B, 0x11, 0x0A, 0x00, 0x00, 0x00 },
   { 0x00, 0x0A, 0x11, 0x1B, 0x11, 0x0A, 0x00, 0x00 },
   { 0x00, 0x00, 0x0A, 0x11, 0x1B, 0x11, 0x0A, 0x00 },
   { 0x00, 0x00, 0x00, 0x0A, 0x11, 0x1B, 0x11, 0x0A },
   { 0x00, 0x00, 0x00, 0x00, 0x0A, 0x11, 0x1B, 0x11 },
   { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x11, 0x1B }
};


//
// Helper functions
//
static void eCxx_user_init_lcdInitAndTest()
{
    lcd.begin(16, 2);

    for(eCxx::uint8_t i = 0; i < eCxx::arraySize(userChars); ++i) {
        lcd.setUserDefinedCharacter( i, eCxx::PGM_PTR(userChars, i) );
    }

    // Test the LCD
    lcd.cursorHome();
    lcd.writeString( PGM_STR("  Hello World!  ") );

    lcd.setCursorPosition(0, 1);
    lcd.writeString( PGM_STR("0123456789ABCDEF") );

    App::delayMS(2500);
}


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

    // ### Perform backlight animation ###
    // static eCxx::uint8_t blc = 0;
    // lcd.setBacklight( (++blc) % 4, false );

    // ### Perform display animation ###
    static eCxx::uint8_t idx = 0;
    static eCxx::uint8_t inc = 1;

    // Write to LCD line 1
    lcd.setCursorPosition(0, 0);
    eCxx::uint8_t chr = idx;
    eCxx::uint8_t dir = 1;
    for(eCxx::uint8_t c = 0; c < 16; ++c) {
        lcd.write(chr);
        if(dir) {
            if(chr < 7) { ++chr;              }
            else        {   chr = 6; dir = 0; }
        }
        else {
            if(chr > 0) { --chr;              }
            else        {   chr = 1; dir = 1; }
        }
    }

    // Write to LCD line 2
    lcd.setCursorPosition(0, 1);
    chr = 7 - idx;
    dir = 1;
    for(eCxx::uint8_t c = 0; c < 16; ++c) {
        lcd.write(chr);
        if(dir) {
            if(chr < 7) { ++chr;              }
            else        {   chr = 6; dir = 0; }
        }
        else {
            if(chr > 0) { --chr;              }
            else        {   chr = 1; dir = 1; }
        }
    }

    // Adjust the start index
    if(inc) {
        if(idx < 7) { ++idx;              }
        else        {   idx = 6; inc = 0; }
    }
    else {
        if(idx > 0) { --idx;              }
        else        {   idx = 1; inc = 1; }
    }
}
