/*

TODO List:

- Add OTA Updates
- Add reset to Factory Defaults
- Add Captive Portal / WiFi HotSpot
- Add manual Sync-Time
- Add NTP Time Sync
- Add the ability to report the list of melodies
- Add the ability to report a month's ScheduleEntry
- Add the ability to report the free space in SPIFFS.
- Add global logger
- Add

*/

#include <WiFi.h>
#include <AsyncMqttClient.h>
#include <ArduinoJson.h>
#include <FS.h>
#include <SPIFFS.h>
#include <string>
#include <Wire.h>
#include <Adafruit_PCF8574.h>
#include "RTClib.h"

// Hardware Constructors:
Adafruit_PCF8574 relays;
RTC_DS1307 rtc;

// Include Classes
#include "classes.hpp"

// Class Constructors
AsyncMqttClient mqttClient;
Player player;
TimeKeeper timekeeper;
std::vector<uint16_t> melody_steps; // holds the steps of the melody. Should move into bell Engine.

#include "config.h"
#include "functions.hpp"
#include "MQTT_Message_Handling.hpp"
#include "MQTT_WiFi_Utilities.hpp"
#include "PlaybackControls.hpp"
#include "bellEngine.hpp"
#include "Scheduler.hpp"

TaskHandle_t bellEngineHandle = NULL;
TimerHandle_t schedulerTimer;



void setup()
{
  // Initialize Serial Communications & I2C Bus (for debugging)
	Serial.begin(115200);
  delay(50);

	// Initialize PCF8574
	Wire.begin(4,15);
	relays.begin(PCF8574_ADDR, &Wire);
	// Initialize Relays
	for (uint8_t p=0; p<6; p++){
		relays.pinMode(p, OUTPUT);
		relays.digitalWrite(p, HIGH);
	}
  // Initialize SPIFFS
  if (!SPIFFS.begin(true)) {  // 'true' means format SPIFFS if initialization fails
    Serial.println("Failed to mount SPIFFS");
    while(true) delay(10);
  }
  Serial.println("SPIFFS mounted successfully");
	delay(50);
  // Initialize RTC
  if (!rtc.begin()) {
  Serial.println("Couldn't find RTC");
  while(true) delay(10);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }


  // Initialize WiFi and MQTT
	WiFi.onEvent(WiFiEvent);
	InitMqtt();
	ConnectWiFi_STA();
  delay(1000);

  xTaskCreatePinnedToCore(bellEngine,"bellEngine", 8192, NULL, 1, &bellEngineHandle, 1);
  xTaskCreatePinnedToCore(durationTimer, "durationTimer", 8192, NULL, 2, NULL, 1);
	xTaskCreatePinnedToCore(relayControlTask, "Relay Control", 2048, NULL, 2, NULL, 1);

	schedulerTimer = xTimerCreate("Timer",pdMS_TO_TICKS(10000),pdTRUE,(void*)0,reinterpret_cast<TimerCallbackFunction_t>(schedule_timer));

	if (schedulerTimer != NULL) {
			xTimerStart(schedulerTimer, 0);
	} else {
			Serial.println("Failed to create timer!");
	}

	timekeeper.refreshDailySchedule();
	loadRelayTimings();

}


void loop()
{
}
