#include "alarm.h"
#include "Dict.h"
#include "Times.h"
#include <Wiegand.h>

class WiegandReader{

private:
  WIEGAND wg;
  AlarmStatus* status;
  int data0_pin;
  int data1_pin;
  int led_pin =0;
  int beep_pin =0;
  Dictionary &users = *(new Dictionary());
  unsigned long errorTime;
  bool beeping = false;

  void turnLedGreen(){
    digitalWrite(led_pin, LOW);
  }
  void turnLedRed(){
    digitalWrite(led_pin, HIGH);
  }
  void beepOn()
  {
    beeping=true;
    digitalWrite(beep_pin, LOW);
  }
  void beepOff()
  {
    beeping=false;
    digitalWrite(beep_pin, HIGH);
  }

public:
  WiegandReader(AlarmStatus* statusObj, int d0, int d1){
    status = statusObj;
    data0_pin = d0;
    data1_pin = d1;
  }
  void Init()
  {
    wg.begin(data0_pin, data1_pin);
  }

  void AddUser(String id, String name){
    users(id, name);
  }

  void SetLed(int pin)
  {
    led_pin=pin;
    pinMode(led_pin, OUTPUT);
    digitalWrite(led_pin, HIGH);
  }
  void SetBeep(int pin)
  {
    beep_pin=pin;
    pinMode(beep_pin, OUTPUT);
    digitalWrite(beep_pin, HIGH);
  }

  void HandleReader()
  {
    if(beeping)
    {
      if(millis() > errorTime + FromSeconds(1))
      {
        beepOff();
      }
      return;
    }
    if(!status->isArmed)
    {
      turnLedGreen();
    }else
    {
      turnLedRed();
    }
    if(!wg.available())
    {
      return;
    }

    String uidString = String(wg.getCode());
    Serial.print("[Card Reader] ");Serial.println(uidString);

    for (int i = 0; i < users.count(); i++) {
      if(users(i) == uidString){
        status->allowed=true;
        status->userAllowed=users[i];
        return;
      }
    }

    Serial.println("[Card Reader] access not granted");
    status->showError =true; 

    errorTime = millis();
    beepOn();
  }

  
};