/* RFID */
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN 9
#define SS_PIN 10
#define SUCCESS_LED A1
#define FAILURE_LED A0

MFRC522 mfrc522(SS_PIN, RST_PIN);

/* LCD */

#include <LiquidCrystal.h>

const int rs = 8, en = 7, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);


void setup() {

  /* LCD */
  lcd.begin(16, 2);
  lcd.print("Please show ID");
  /* RFID */
  pinMode(SUCCESS_LED, OUTPUT);
  pinMode(FAILURE_LED, OUTPUT);
  Serial.begin(9600);
  while (!Serial);
  SPI.begin();
  mfrc522.PCD_Init();
  mfrc522.PCD_DumpVersionToSerial();
  Serial.println(F("Scan PICC to see UID, type, and data blocks..."));

}

void loop() {
  lcd.setCursor(0, 0);
  if (mfrc522.PICC_IsNewCardPresent() ) { // Card is detected
    Serial.println(F("Card Detected.."));
    unsigned long uid = getID();
    if(uid != -1){
      String idNumber = String(uid);
      Serial.print("Card detected, UID: "); Serial.println(uid);
      if(uid == 22020){                                           // Case where card is denied
        lcd.print("Access Denied");
        lcd.setCursor(0, 1);
        lcd.print(idNumber);
        Serial.println(F("Access Denied.."));
        LED_alarm();
      }
      else {                                                      // Case where card is accepted
        lcd.print("Access Granted");
        lcd.setCursor(0, 1);
        lcd.print(uid);      
        Serial.println(F("Access Granted.."));
        for (int i=0; i<3; i++){
          digitalWrite(SUCCESS_LED, HIGH);
          delay (500);
          digitalWrite(SUCCESS_LED, LOW);
          delay (200);
        }
      }
    }
    //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
    return;
  }

  else {                                                // Reset LCD
    lcd.setCursor(0, 1);
    lcd.print("             ");
    lcd.setCursor(0, 0);
    lcd.print("Please show card");
    delay (1000);
    digitalWrite(FAILURE_LED, HIGH);
    delay (1000);
    digitalWrite(FAILURE_LED, LOW);
    Serial.println(F("Not yet.."));
    return;
  }

  
  
}
// Allows to get ID
unsigned long getID(){
  if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue
    return -1;
  }
  unsigned long hex_num;
  hex_num =  mfrc522.uid.uidByte[0] << 24;
  hex_num += mfrc522.uid.uidByte[1] << 16;
  hex_num += mfrc522.uid.uidByte[2] <<  8;
  hex_num += mfrc522.uid.uidByte[3];
  mfrc522.PICC_HaltA(); // Stop reading
  return hex_num;
}

void LED_alarm(){
  for (int i=0; i<8; i++){
    delay (100);
    digitalWrite(FAILURE_LED, HIGH);
    digitalWrite(SUCCESS_LED, LOW);
    delay (100);
    digitalWrite(FAILURE_LED, LOW);
    digitalWrite(SUCCESS_LED, HIGH);
  }
  digitalWrite(SUCCESS_LED, LOW);


}
