/// © MiroZ 2024

#include "App.h"

#include <Arduino.h>
#include "Settings.h"
#include "errors.h"

#include "Ota.h"
#include "ProvisionSoftAP.h"


#define LED_PIN	26

static const char * TAG = "app";

App::App()
{

}

Led * App::getLed()
{
	return m_led;
}

CircBuffer * App::getBuffer()
{
	return & m_circ_buffer;
}

void App::init()
{
	ESP_LOGW(TAG, "Starting the app...");

	m_led = new Led(LED_PIN);
	m_wifi = new Wifi();
	
#if 1

	bool needs_provision = true;

	if(SETTINGS.wifi.num > 0)
	{
		// try connecting
		m_led->setColor(0, 255, 0);
		m_wifi->start();

		Wifi::WIFI_STATUS wifi_status = m_wifi->waitForConnection();

		if(wifi_status == Wifi::WIFI_STATUS::CONNECTED)
		{
			ESP_LOGI(TAG, "Getting local time...");
			struct tm timeinfo;

			int tries = 5;
			while (tries--)
			{
				configTime(0, 0, "pool.ntp.org");	// needed?

				if(getLocalTime(&timeinfo))
				{
					ESP_LOGI(TAG, "ok");
					break;
				}
				else
					ESP_LOGE(TAG, "Failed");
			}
    		
			needs_provision = false;
		}
	}
	
	if(needs_provision)
	{
		m_led->setPulse(0, 0, 255);
		ProvisionSoftAP provision(80);
		provision.start();
	}

	otaCheck();
	
	m_led->setPulse(255, 0, 255);

	m_mqtt = new Mqtt(*this);
	m_mqtt->start();

	m_ble = new Ble(*this);
	m_ble->start();

#endif

	m_sensors = new Sensors(*this);
	m_sensors->start();
}

void App::otaCheck()
{
	Ota ota(*this);
	ota.start();
}

void App::start()
{

}

void App::readSensors()
{

}

void App::reportSensors()
{

}