#include <LiquidCrystal.h>
#include <Keypad.h>
#include "icons.h"
#include <LiquidMenu.h>
#include <AsyncTimer.h>

AsyncTimer t;
/* Display */
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);

/* Keypad setup */
const byte KEYPAD_ROWS = 4;
const byte KEYPAD_COLS = 4;
byte rowPins[KEYPAD_ROWS] = {5, 4, 3, 2};
byte colPins[KEYPAD_COLS] = {A3, A2, A1, A0};
char keys[KEYPAD_ROWS][KEYPAD_COLS] = { {'1', '2', '3', 'A'},{'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},{'S', '0', 'R', 'D'}};

char kc = 'x';
char km = 'w';
bool hasNewKey = false;
String msg;
byte ledPin = 13;

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, KEYPAD_ROWS, KEYPAD_COLS);

LiquidLine welcome_line2(1, 1, "Functions ex.");

void functionToCall()
{
    digitalWrite(ledPin, LOW);
}


void showStartupMessage() {
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("Welcome..!");
  delay(1000);

}

String inputSecretCode() {
  lcd.setCursor(5, 1);
  lcd.print("[____]");
  lcd.setCursor(6, 1);
  String result = "";
  while (result.length() < 4) {
    char key = keypad.getKey();
    if (key >= '0' && key <= '9') {
      lcd.print(key);
      result += key;
    }
  }
  return result;
}

void showWaitScreen(int delayMillis) {
  lcd.setCursor(2, 1);
  lcd.print("[..........]");
  lcd.setCursor(3, 1);
  for (byte i = 0; i < 10; i++) {
    delay(delayMillis);
    lcd.print("=");
  }
}

void setup() {
  lcd.begin(16, 2);
  init_icons(lcd);
  pinMode(ledPin, OUTPUT);
  showStartupMessage();
  Serial.begin(115200);
}

void loop()
{
    // Fills kpd.key[ ] array with up-to 10 active keys.
    // Returns true if there are ANY active keys.
    if (keypad.getKeys())
    {
        for (int i = 0; i < LIST_MAX; i++) // Scan the whole key list.
        {
            if (keypad.key[i].stateChanged) // Only find keys that have changed state.
            {
                switch (keypad.key[i].kstate)
                { // Report active key state : IDLE, PRESSED, HOLD, or RELEASED
                case PRESSED:
                    msg = " PRESSED.";
                    digitalWrite(ledPin, HIGH);
                    t.setTimeout(functionToCall, 20);
                    kc = keypad.key[i].kchar;
                    //km = 'P';
                    hasNewKey = true;
                    break;
                case HOLD:
                    msg = " HOLD..";
                    break;
                case RELEASED:
                    msg = " RELEASED.";
                    break;
                case IDLE:
                    msg = " IDLE.";
                }

                Serial.print("Key ");
                Serial.print(keypad.key[i].kchar);
                Serial.println(msg);
            }
        }
    }

    t.handle();

}