/*
 * Firewatch.h
 *
 *  Created on: Feb 28, 2025
 *      Author: Murdock
 */

#ifndef FIREWATCH_H_
#define FIREWATCH_H_

#include <Arduino.h>
#include "common.h"
#include "DHTAsyncSensors.h"
#include "SettingsManager.h"
#include "MQ2GasSensorNonBlocking.h"
#include "LCDHelper.h"

class FireWatch {
private:
	DHTAsyncSensors* dhtSensors;
	SettingsManager* settingsManager;
	MQ2GasSensorNonBlocking* gasSensor;
	LCDHelper* lcdHelper;

	byte powerRelayPIN;
	byte buzzerPIN;

	// Fire alarm siren settings
	byte fireAlarmSirenMinFrequency;
	word fireAlarmSirenMaxFrequency;
	word fireAlarmSirenCycleTime;
	byte sirenUpdateInterval; // Time between frequency steps in milliseconds

	//warning siren settings
	word warningSirenFrequency;
	word warningSirenBeepDuration;
	word warningSirenPauseDuration;
	bool isWarningBeeping;

	unsigned long sirenLastUpdateTime;
	unsigned long sirenStartTime;

	word sirenCurrFrequency;
	word alarmPPM;

	byte statusLEDPIN;
	bool statusLEDState;
	unsigned long statusLEDLastUpdateTime;

	FireAlertMode currentAlertMode;
	bool bAlertModeChangedFromSettings;

	void triggerFireAlarm();
	void resetFireAlarm();
	void toneFireAlarmSiren();
	void toneWarningSiren();
	void switchPowerRelay(bool bOn, const char *lcdMessage, word waitTime);

	void handleAlert(FireAlertMode prevMode, FireAlertMode currMode);

	void updateStatusLED();

public:
	FireWatch(DHTAsyncSensors* dhtSensors, SettingsManager* settingsManager, MQ2GasSensorNonBlocking* gasSensor, LCDHelper* lcdHelper, byte powerRelayPIN, byte buzzerPIN, byte statusLEDPIN);

	void attach();
	/**
	 * This function checks for fire hazard based on stored
	 */
	void doFireWatch();

	bool isPowerRelayOn();
	FireAlertMode getAlertMode() const { return currentAlertMode; }

	MQ2GasSensorNonBlocking* getGasSensor() const { return gasSensor; }
	DHTAsyncSensors* getDHTSensors() const { return dhtSensors; }
	SettingsManager* getSettingsManager() const { return settingsManager; }

	/**
	 * Checks whether there was a stored file alarm and switched power relay ON/OFF
	 */
	void checkStoredFireAlarm();
	void switchPowerRelayOn();
	void switchPowerRelayOff();
	void setAlertMode(FireAlertMode currMode, bool bChangedFromSettings);
};

#endif /* FIREWATCH_H_ */
