#include <LiquidCrystal.h>
#include <Keypad.h>
#include <Servo.h>
#include "SafeState.h"
#include "icons.h"

#define SERVO_PIN 6
#define SERVO_LOCK_POS 20
#define SERVO_UNLOCK_POS 90
Servo lockServo;

LiquidCrystal lcd(12, 11, 10, 9, 8, 7);

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'}, {'*', '0', '#', 'D'}};

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

const int SCAN_BUTTON_PIN = 13; // Pin for the simulated barcode scanner button

void setup() {
  // Initialize LCD and icons
  lcd.begin(16, 2);
  init_icons(lcd);

  // Display the random number on LCD during setup
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Random Number:");
  lcd.setCursor(0, 1);
  lcd.print(safe.generateRandomNumber());
  delay(2000); // Adjust delay time as needed
  lcd.clear();

  // Set up the scan button
  pinMode(SCAN_BUTTON_PIN, INPUT_PULLUP);
}

void loop() {
  // Check for keypad input
  char key = keypad.getKey();
  if (key) {
    if (key == '#') {
      // Check if the entered code matches the random number
      String enteredCode = "";
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Enter Code:");
      lcd.setCursor(0, 1);

      // Read the entered code from the keypad
      while (enteredCode.length() < 4) {
        char key = keypad.getKey();
        if (key) {
          enteredCode += key;
          lcd.print('*'); // Display asterisks for each entered digit
        }
      }

      // Check if the entered code matches the random number
      if (enteredCode.toInt() == safe.generateRandomNumber()) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Correct Code!");
        delay(2000); // Adjust delay time as needed
        safe.unlock(enteredCode); // Unlock the safe
      } else {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Incorrect Code!");
        delay(2000); // Adjust delay time as needed
      }

      lcd.clear();
    }
  }

  // Simulate barcode scanning when the button is pressed
  if (digitalRead(SCAN_BUTTON_PIN) == LOW) {
    String scannedBarcode = "123456"; // Replace with actual scanned barcode data
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Scanned Barcode:");
    lcd.setCursor(0, 1);
    lcd.print(scannedBarcode);
    delay(2000); // Adjust delay time as needed
    lcd.clear();
  }

  // Add any other necessary code for the main loop
}