#include <iostream>
#include <vector>

#include "FileSys.hpp"
#include "Logger.hpp"
#include "RTClock.hpp"
#include "StateVariables.hpp"
#include "BSP.hpp"
#include "StateBase.hpp"

bool createAllFiles();
bool writeFileHeaders();

bool Logger::init()
{
	createAllFiles();
	writeFileHeaders();
	
	return true;
}

std::string_view Logger::getStateLabel()
{
	return StateBase::getStateLabel();
}

bool writeFileHeaders()
{
	std::cout << "Logger writeFileHeaders()" << std::endl;
	BSP::gps1.logEngFileHeader();
	StateBase::logEngFileHeader();
	
	return true;
}

bool createAllFiles()
{
	tm dtStruct = RTClock::getDateTimeStruct();
	char dirName[48] = { 0 };
	bool returnValue;

	snprintf(dirName,
		sizeof(dirName),
		"/Mission%d%s%02dT%02d%02d%02d",
		dtStruct.tm_year + 1900,
		RTClock::getMonthText(dtStruct.tm_mon).data(),
		dtStruct.tm_mday,
		dtStruct.tm_hour,
		dtStruct.tm_min,
		dtStruct.tm_sec); 
	
	uint16_t currentProfileNum = StateVariables::getProfileNum();
	
	if (currentProfileNum == 0)
	{
		returnValue = FileSys::createDir(dirName);
		if (returnValue)
		{
			std::cout << "Logger openAllFiles created new dir name: " << dirName << "  FatFs return value: " << returnValue << std::endl;
		}
		else
		{
			std::cout << "**ERROR: Logger openAllFiles FAILED to create new dir name: " << dirName  << "  FatFs return value: " << returnValue << std::endl;
		}
	}
	
	char fPath[65];
	snprintf(fPath,
		sizeof(fPath),
		"%s/CPF010.%03d.eng",
		dirName,
		currentProfileNum);
	
	const std::string filePath{fPath};
	
	returnValue = FileSys::createFile(FileSys::engFile, filePath);
	if (returnValue)
	{
		std::cout << "Logger openAllFiles created new eng file name: " << dirName  << "  FatFs return value: " << returnValue << std::endl;
	}
	else
	{
		std::cout << "**ERROR: Logger openAllFiles FAILED to create new file name: " << dirName  << "  FatFs return value: " << returnValue << std::endl;
	}
	
//	f_close(&SDFile);
//	fileSysReady = true;
	return returnValue;
}
	
void Logger::logEngLine(bool sendToBT, std::initializer_list<std::string_view> svList)
{
	auto svBegin = svList.begin();
	auto svEnd = svList.end();
	std::string line;
	std::string delimiter = "\t";
	std::string stx = "$";
	std::string etx = "\r\n";

	line.append(stx);
	line.append(delimiter);
	for (auto i = svBegin; i != svEnd; i++)
	{
		line.append(*i);
		line.append(delimiter);
	}
	line.append(etx);
	
	FileSys::writeLine(FileSys::engFile, line);
	
	if (sendToBT)
	{
		//send to Bluetoooth when implemented
		std::cout << "Logger::logEngLine-> " << line << std::endl;
	}
		
}