#include <stdio.h>

#include "IdiBusSlave.h"
#include "IDIBUS_IMPL.h"
#include "Serial.h"
#include "DS3231.h"
#include "time.h"
#include "fs.h"
#include "spi.h"
#include "sd.h"
//Structure that holds module's data
XXX_NAME_channel_data_t XXX_NAME_channels_data[IDIBUS_XXX_NAME_CH_NUM];

static void custom_init()
{

}
static void custom_shutdown()
{

}
static void custom_freeze()
{

}
static void custom_resume()
{

}

void SlaveInit() // Intr is ON
{
    IdiBus_register_init(custom_init);
    IdiBus_register_shutdown(custom_shutdown);
    IdiBus_register_freeze(custom_freeze);
    IdiBus_register_resume(custom_resume);

    Debug.begin(57600);
    Debug.writeln("Program start");
    
    initDS3231();
    Debug.writeln("Clock RTC Init");
    
    spi_init();
    if (!sd_init())
	{
		Debug.writeln("SD ready");
	}
	else
	{
		Debug.writeln("SD failed");
	}

	Debug.writeln("Initializing file system... ");
	if (!fs_init())
	{
		Debug.writeln("FS ready");
	}
	else
	{
		Debug.writeln("FS failed");
	}

	Debug.writeln("file system type: ");
	if (fs_type == 1)
	{
		Debug.writeln("FAT32");
	}
	else if (fs_type == 0)
	{
		Debug.writeln("FAT16");
	}
	else Debug.writeln("UNKNOWN");
}
static int16_t temperature; // For whatever reason...
void updateTimeFromRtc()
{
	static uint32_t timestamp_read = 0;
	static const uint32_t PERIOD_MS = 1000;
	if (System_GetSysTickDifference(timestamp_read) > PERIOD_MS)
	{

		temperature = ds3231GetTemperature();

		char buf[64] = {0};
		sprintf(buf, "Date %d:%d:%d - %d.%d.%d Temp:%i",
		        ds3231GetHour(), ds3231GetMinute(), ds3231GetSecond(),
		        ds3231GetDate(), ds3231GetMonth(), ds3231GetYear(),
		        temperature);
		Debug.writeln(buf);
		timestamp_read = System_GetSysTick();
	}
}
void SlaveLoop()
{
	//Read any data that can change in channels data
	updateTimeFromRtc();

	//Do some app logic
	//..
	//Update channel data
	//Exit
}