//! Door lock system
//!

#![no_std]
#![no_main]

use esp_backtrace as _;
use esp_hal::{
  delay::Delay,
  gpio::{Input, Level, Output, Pull},
  ledc::{channel, timer, LSGlobalClkSource, Ledc, LowSpeed},
  prelude::*
};
use esp_println::println;

const CODE: [char; 4] = ['1', '2', '3', '4']; 

#[entry]
fn main() -> ! {
    let peripherals = esp_hal::init(esp_hal::Config::default());
    let delay = Delay::new();

    // LEDs
    let mut led_red = Output::new(peripherals.GPIO22, Level::Low);
    let mut led_green = Output::new(peripherals.GPIO23, Level::Low);

    
    // rows
    let mut rows = [
      Output::new(peripherals.GPIO19, Level::Low),
      Output::new(peripherals.GPIO18, Level::Low),
      Output::new(peripherals.GPIO5, Level::Low),
      Output::new(peripherals.GPIO17, Level::Low)
    ];
    // cols
    let mut cols = [
      Input::new(peripherals.GPIO16, Pull::Up),
      Input::new(peripherals.GPIO4, Pull::Up),
      Input::new(peripherals.GPIO2, Pull::Up),
    ];

    esp_println::logger::init_logger_from_env();

    let mut input_code: [char; 4] = [' '; 4];
    let mut current_index = 0;

    loop {
      for (row_index, row) in rows.iter_mut().enumerate() {
          // Active la ligne courante
          row.set_low();

          for (col_index, col) in cols.iter().enumerate() {
              // Vérifie si une touche est pressée
              if col.is_low() {
                let key = key_pressed(row_index, col_index);
                  // Affiche la touche détectée
                  esp_println::println!("Touche pressée : {}", key);
                  
                  // Ajoute la touche pressée
                  if current_index < input_code.len() {
                      input_code[current_index] = key;
                      current_index += 1;
                  }

                  // Si input_code is full, on vérifie le code
                  if current_index == input_code.len() {

                      if input_code == CODE {
                        println!("CODE CORRECT !");
                        led_green.set_high();
                        delay.delay_millis(500);
                      } else {
                        println!("CODE INCORRECT !");
                        led_red.is_set_high();
                        delay.delay_millis(500);
                      }

                      // Réinitialise le tableau et l'index
                        input_code = [' '; 4];
                        current_index = 0;
                  }
              }
          }

          // Désactive la ligne courante
          row.set_high();
      }
  }
}


fn key_pressed(row_index: usize, col_index: usize) -> char {
  // Keypad
    let keypad = [
      ['1', '2', '3'],
      ['4', '5', '6'],
      ['7', '8', '9'],
      ['*', '0', '#'],
    ];

    keypad[row_index][col_index]
}
$abcdeabcde151015202530fghijfghij