#include <SmingCore.h>

///////////////////////////////////////////////////////////////////
// Set your SSID & Pass for initial configuration
#include "configuration.h" // application configuration
///////////////////////////////////////////////////////////////////

#include "webserver.h"
#include "tm1650.h"

Timer procTimer, procRTimer;
Timer displayTimer, tmpTimer;
Timer showHighTimer, showLowTimer;
Timer brightTimer;
// Sensors string values
float SensorT, SensorH, SensorHI, SensorCR;
String StrCF;
// Time values
time_t Time, NTPLastUpdate;
DateTime dt;

void process(void);
void connectOk(const String& SSID, MacAddress bssid, uint8_t channel);
void connectFail(const String& ssid, MacAddress bssid, WifiDisconnectReason reason);
void gotIP(IpAddress ip, IpAddress netmask, IpAddress gateway);

void showWatch(void);
void showTime(void);
void showTemperature(void);
void showHumidity(void);
void setBright(void);

// NTP Client
void onNtpReceive(NtpClient& client, time_t timestamp);
NtpClient ntpClient("ntp.time.in.ua", 1500, onNtpReceive); // every 15 min

void init()
{
	spiffs_mount(); // Mount file system, in order to work with files

	Serial.begin(SERIAL_BAUD_RATE);  // 115200 by default
	Serial.systemDebugOutput(false); // Debug output to serial
	Serial.println("Wall Segment Clock");

	ActiveConfig = loadConfig();

	// set timezone hourly difference to UTC
	SystemClock.setTimeZone(ActiveConfig.AddTZ);

	WifiStation.config(ActiveConfig.NetworkSSID, ActiveConfig.NetworkPassword);
	WifiStation.enable(true);
	WifiAccessPoint.enable(false);

	WifiEvents.onStationConnect(connectOk);
	WifiEvents.onStationDisconnect(connectFail);
	WifiEvents.onStationGotIP(gotIP);

	// Sensors start
	//dht.begin();

	// polling sensors - once a minute?
	procTimer.initializeMs(60000, process).start();
	process();

	// Low LED output
	TM1650_Init();
	brightTimer.initializeMs(1000, setBright).start();

	// обновление экрана два раза в секунду
	displayTimer.initializeMs(500, showWatch).start();
}

void showWatch(void) {
	static time_t oldTime;

	Time = SystemClock.now();

	dt.setTime(Time);

	/*
	 * теперь в dt у нас следующее:
	 * 	int8_t Hour;
	 * 	int8_t Minute;
	 * 	int8_t Second;
	 * 	int16_t Milliseconds;
	 * 	int8_t Day;
	 * 	int8_t DayofWeek; -- Sunday is day 0
	 * 	int8_t Month; // Jan is month 0
	 * 	int16_t Year;  // Full Year numer
	 */

	if (oldTime == Time) {
		// Старая секунда - нужно гасить точки
		TM1650_DotRes(Dig_2);
	}	else {
		// Новая секунда
		oldTime = Time;
		TM1650_Out(dt.Hour >> 4, dt.Hour & 0xf, dt.Minute >>4, dt.Minute & 0xf);
		TM1650_DotSet(Dig_2);
	}
}

/*
 * Выводим текущее время [HH MM] на верхние индикаторы
 */
void showTime(void) {
	static uint8_t oldHour = 0xFF, oldMinute = 0xFF;

	if (oldMinute != dt.Minute) {
		oldMinute = dt.Minute;

		// ...
		
		if (oldHour != dt.Hour) {
			oldHour = dt.Hour;

			// ...
		} // new hour
	} // new minute
}

/*
 * Выводим температуру на нижние индикаторы
 */
void showTemperature(void) {
		// ...
}

/*
 * Выводим влажность на нижние индикаторы
 */
void showHumidity(void) {
		// ...
}

/*
 * Выводим дату на верхние индикаторы [DD MM]
 */
 void showDate(void) {
 		// ...
}

/*
 * Автоматическая регулировка яркости индикаторов
 * GY-49
 */
void setBright(void) {
		// ...
}

/**
 * @brief Get data from Temperature/Humidity Sensor
 * Currently planed AHT10. Пока заглушка.
 */
void process() {
	float t = 25.0;
	float h = 60.5;

	Serial.print("Humidity: ");
	Serial.print(h);
	Serial.print("%. Temperature: ");
	Serial.print(t);
	Serial.println("*C");
}

void connectOk(const String& SSID, MacAddress bssid, uint8_t channel)
{
	debugf("connected");
	WifiAccessPoint.enable(false);
}

void gotIP(IpAddress ip, IpAddress netmask, IpAddress gateway)
{
	Serial.print("Got IP address: ");
	Serial.println(ip);
	// Restart main screen output
	procTimer.restart();
	displayTimer.restart();

	// start NTP Client there?

	startWebServer();
}

void connectFail(const String& ssid, MacAddress bssid, WifiDisconnectReason reason)
{
	debugf("connection FAILED: %s", WifiEvents.getDisconnectReasonDesc(reason).c_str());
	WifiAccessPoint.config("ClockConfig", "", AUTH_OPEN);
	WifiAccessPoint.enable(true);
	// Stop main screen output
	procTimer.stop();
	displayTimer.stop();

	Serial.println("WiFi ClockConfig");
	Serial.println(WifiAccessPoint.getIP());

	startWebServer();
	WifiStation.disconnect();
	WifiStation.connect();
}

/**
 * @brief NTP Client
 */
void onNtpReceive(NtpClient& client, time_t timestamp)
{
	SystemClock.setTime(timestamp, eTZ_UTC);
	NTPLastUpdate = SystemClock.now();
	Serial.println("*** Time synchronized OK! ***"); // DEBUG
}
