#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Keypad.h>
#include <ESP32Servo.h>
const int ledPin = 15; // Define the LED pin
const int ledPin2 = 17; // Define the LED pin
const int upPin = 32; // Define the button pin
const int downPin = 33; // Define the button pin
const int okPin = 35; // Define the button pin
const int canPin = 34; // Define the button pin


const int rows=4;
const int cols=4;
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);
Servo myservo;
char keys[rows][cols] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

char chars[4][3][5] = {
  {
    { '1', '1', '1', '1', '1'},
    { 'A', 'B', 'C', '2', '2'},
    { 'D', 'E', 'F', '3', '3'}
  },
  {
    { 'G', 'H', 'I', '4', '4'},
    { 'J', 'K', 'L', '5', '5'},
    { 'M', 'N', 'O', '6', '6'}
  },
  {
    { 'P', 'Q', 'R', '7', '7'},
    { 'S', 'T', 'U', '8', '8'},
    { 'W', 'X', 'Y', 'Z', '9'}
  },
  {
    { '*', '*', '*', '*', '*'},
    { ' ', ' ', ' ', ' ', ' '},
    { '#', '#', '#', '#', '#'}
  }    
};

String menus[100][100] =
{
  {
    "SETUP WIFI NAME",
    "SETUP WIFI PASSWORD",
    "SETUP ID KOLAM",
    "MENU ONLINE",
    "MENU OFFLINE"
  },
  {
    "   CEK SENSOR",
    "   PORTABLE TEST",
    "   REAL TIME TEST",
    "   SETTING"
  },
  {
    "   CEK SENSOR",
    "   PORTABLE TEST"
    "   SETTING"
  }    
};

uint8_t colpins[cols] = {2, 0, 4, 16 };
uint8_t rowpins[cols] = {12, 14, 27, 26};

Keypad keypad = Keypad(makeKeymap(keys), rowpins, colpins, rows, cols);
const String password = "1234"; 
String inputan;
Servo servo_bin;
int mode; // mode keypad numeric = 0 mode char = 1
int len; // panjang karakter hasil
int ichar; // index terakhir hasil
char oldkey; // temp keypad
int besar; // mode capslock = 1

boolean now_up = false;
boolean now_down = false;
boolean now_ok = false;
boolean now_can = false;
boolean old_up = false;
boolean old_down = false;
boolean old_ok = false;
boolean old_can = false;


int modeMenu; // jika sedang akses menu = 1 ; jika entry = 0.
int menu; // mencatat posisi menu saat ini
int menu_a; // mencatat posisi menu dimensi 1
int menu_b; // mencatat posisi menu dimensi 2
int setmenu = 0;
String headerMenu;

String namaWifi = " ";
String passWifi = " ";
String idKolam = " ";
void setup(){
  servo_bin.attach(19);
  pinMode(ledPin, OUTPUT); // Set the LED pin as an output
  pinMode(ledPin2, OUTPUT); // Set the LED pin as an output

  pinMode(upPin,   INPUT_PULLUP);
  pinMode(downPin,   INPUT_PULLUP);
  pinMode(okPin, INPUT_PULLUP);
  pinMode(canPin, INPUT_PULLUP);

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.setTextColor(WHITE,BLACK);
  clearLayar();
  Serial.begin(115200);
  inputan.reserve(32);
  mode = 0; // angka 1 = huruf
  len = 0;
  besar = 0;

  headerMenu = " ";
  modeMenu = 1;
  menu_a = 0;
  menu_b = 0;
  setmenu = 0;
}
void splashScreen(){
  display.clearDisplay();
  display.setCursor(0,15);  
  display.setTextSize(6);
  display.print("TAMBAQ IOT 0.1");
  display.display();
  delay(5000);
  display.clearDisplay();
}
void clearLayar(){
  display.setCursor(0,5);
  display.clearDisplay();
  display.setTextSize(2);
  display.print(headerMenu);
  display.display();
}

void keypadAction()
{
  char key = keypad.getKey();
  
  if (key) 
  {
    Serial.println(key);
    /*
    A = OK
    B = CANCEL
    C = HURUF / ANGKA
    D = Delete Char
    */
    if (mode == 0) 
    {
      
      if (key == '*') {

      }
      else if (key == '#') {

      }
      else if(key == 'A') {
        // OK
      }
      else if(key == 'B') {
        // CANCEL
      }
      else if(key == 'C') {
        mode = 1;
        ichar = 0;
        oldkey = 'C';
        Serial.println('s');
        analogWrite(ledPin, 255); // Turn on the LED
      }
      else if(key == 'D') {
        if (len > 0) {
          len--;
          inputan = inputan.substring(0, len-1);
          clearLayar();
          display.print(inputan);
          display.display();
        }       
      }
      else {
        // clearLayar();
        display.print(key);
        display.display();
        inputan += key; 
        len++;
      }      
    }
    else if (mode == 1)
    {
      // reset index array
      if (ichar == 5)
      {
        ichar = 0;
      }

      if (key == 'C' )
      {
        mode = 0;
        ichar = 0;
        oldkey = 'C';
        Serial.println('p');
        besar = 0;
        digitalWrite(ledPin2, LOW); // Turn off the LED
        digitalWrite(ledPin, LOW); // Turn off the LED
        delay(1000);  // Tunggu 1 detik
        
      }      
      else if (oldkey == 'C')
      {
       //  oldkey = key;
        ichar = 0;
      }
      
      if (mode == 1)
      {
        char h = '&';
        if (key == '2')
        {
          h = chars[0][1][ichar];
        }
        else if (key == '3')
        {
          h = chars[0][2][ichar];
        }
        else if (key == '4')
        {
          h = chars[1][0][ichar];
        }
        else if (key == '5')
        {
          h = chars[1][1][ichar];
        }
        else if (key == '6')
        {
          h = chars[1][2][ichar];
        }
        else if (key == '7')
        {
          h = chars[2][0][ichar];
        }
        else if (key == '8')
        {
          h = chars[2][1][ichar];
        }
        else if (key == '9')
        {
          h = chars[2][2][ichar];
        }
        else if (key == '0')
        {
          h = chars[3][1][ichar];
        }
        else if (key == 'A')
        {
          // OK
        }
        else if (key == 'B')
        {
          // CANCEL
        }
        else if (key == 'D')
        {
          if (len > 0) {
            len--;
            inputan = inputan.substring(0, len-1);
            clearLayar();
            display.print(inputan);
            display.display();
            mode = 1;
            ichar = 0;
            oldkey = 'C';
          }      
        }
        else if (key == '*')
        {
          if(besar == 0)
          {
            besar = 1;
            digitalWrite(ledPin2, 255); // Turn on the LED
          }
          else
          {
            besar = 0;
            digitalWrite(ledPin2, LOW); // Turn on the LED
            delay(1000);
          }
        }

        if (h == '&')
        {
          
        }
        else if (key == oldkey)
        {
          if (key != '0')
          {
            len--;
            inputan = inputan.substring(0, len-1);            
          }
          if (besar == 0)
          {
            h = tolower(h);
          }
          inputan += h;   
          len++;
          ichar++;
        }
        else
        {
          if (besar == 0){
            h = tolower(h);
          }
          inputan += h;   
          len++;
          oldkey = key;
          ichar = 0;
        }  
        clearLayar();
        display.print(inputan);
        display.display();     
      }    

    }
    delay(10);
  }
}
void okAction()
{
  if (menu_a == 0 && menu_b == 0)
  {
    
    namaWifi = inputan;
    // cek WIFI BAGAIMANA jika ok lanjut ke menu selanjutnya
    inputan = "";
    menu_a = 0;
    menu_b = 1;
    headerMenu = menus[menu_a][menu_b];
    clearLayar();
    modeMenu = 0;
  }
  else if (menu_a == 0 && menu_b == 1)
  {
    
    passWifi = inputan;

    // cek wifi password dan buat koneksi 
    inputan = "";
    menu_a = 0;
    menu_b = 2;
    headerMenu = menus[menu_a][menu_b]; // lempar ke setting kolam
    clearLayar();
    modeMenu = 0;
  }
  else if (menu_a == 0 && menu_b == 2)
  {
    idKolam = inputan;
    // cek id kolam dulu 
    inputan = "";
    menu_a = 0;
    menu_b = 3;
    headerMenu = menus[menu_a][menu_b]; // lempar ke halaman menu online
    clearLayar();
    modeMenu = 1;
    setmenu = 0;
    showMenuOnline();
  }
  else if(menu_a == 0 && menu_b == 3)
  {
    headerMenu = menus[1][setmenu];
    clearLayar();
    modeMenu = 0;
   /* 
   // isi dengan menu masing2 transaksi 
   if (setmenu == 0)
    {
      
    }
    else if (setmenu == 1)
    {

    }
    else if (setmenu == 2)
    {

    }
    else if (setmenu == 3)
    {

    } */
  }
}

void showMenuOnline()
{
  int j = 3 ;
  if (menu_a == 2)
  {
    j = 2;
  }
  for (int i = 0; i <= j; i++)
  {
    String str = menus[menu_a][i];
    if (setmenu == i)
    {
       str =  '>' + str.substring(1, str.length() - 1); 
    }
  }
}


void buttonAction()
{
  now_up   = digitalRead(upPin);
  now_ok   = digitalRead(okPin);
  now_down = digitalRead(downPin);
  now_can = digitalRead(canPin);
  if (now_up != old_up)
  {
    old_up = now_up;
    if (now_up == false)
    {
      // ini untuk action button ok 
      okAction();
    }
    delay(10);
  }
}

void loop()
{
  tampil();
  if (modeMenu == 0)
  {
    keypadAction();
  }
  buttonAction();
}

void menu_0_0()
{ // set wifi
  splashScreen();
  headerMenu = menus[0][0];
  clearLayar();
  modeMenu = 0;    
}
void menu_0_1()
{ // set wifi password 
  splashScreen();
  headerMenu = menus[0][1];
  clearLayar();
  modeMenu = 0;    
}

void tampil()
{
  clearLayar();
  if (menu_a == 0 && menu_b == 0)
  {
    menu_0_0();
  }
}