#include "alarm.h"
#include "Times.h"

AlarmStatus* status;

class DoorSensor {
  
private:
  int DOOR_SENSOR_PIN = 14;
  AlarmStatus* status;
  int lastDoorState = 1; // Last instantaneous reading
  unsigned long lastDebounceTime = 0; // Time when a change was first detected

public:

  static const int DEFAULT_DOOR_SENSOR_PIN=14;

  DoorSensor(AlarmStatus* statusObj, int doorSensorPin){
    DOOR_SENSOR_PIN = doorSensorPin;
    status = statusObj;
  }
  DoorSensor(AlarmStatus* statusObj){
    DOOR_SENSOR_PIN = DEFAULT_DOOR_SENSOR_PIN;
    status = statusObj;
  }
  void Init(){
    pinMode(DOOR_SENSOR_PIN, INPUT_PULLUP);
    status->doorStatus = digitalRead(DOOR_SENSOR_PIN);
    lastDoorState = status->doorStatus;
  }

  bool IsDoorOpen(){
    return status->doorStatus == DOOR_OPEN;
  }
  bool IsDoorClosed(){
    return status->doorStatus == DOOR_CLOSED;
  }

  void HandleDoor(){
    // Read the current state of the door sensor
    int reading = digitalRead(DOOR_SENSOR_PIN);

    // If the reading has changed from the previous instantaneous reading,
    // reset the debounce timer.
    if (reading != lastDoorState) {
      lastDebounceTime = millis();
    }
    
    // If the new reading has remained stable longer than the debounce delay,
    // then update the door state.
    if ((millis() - lastDebounceTime) >= FromSeconds(1)) {
      // If the reading is different from the last stable door state,
      // update the status and mark that a change has occurred.
      if (reading != status->doorStatus) {
        status->doorStatus = reading;
        status->doorChanged = true;
      }
    }

    // Save the current reading for the next iteration.
    lastDoorState = reading;
  }
};
