/*
 * Mirai. Copyright (C) 2024 Vyn
 * This file is licensed under version 3 of the GNU General Public License (GPL-3.0-only)
 * The license can be found in the LICENSE file or at https://www.gnu.org/licenses/gpl-3.0.txt
 */

#include "StdFileSource.h"
#include "TodoMd.h"
#include <fstream>
#include <iostream>
#include <ostream>
#include <string>

namespace mirai
{

void StdFileSource::save()
{
	std::ofstream file(getPath());
	if (!file.is_open()) {
		throw std::runtime_error("can't create " + getPath());
	}

	const std::string content = TodoMdFormat::stringify(getName(), *days());

	file << content;
	file.close();
};

void StdFileSource::load()
{
	std::ifstream file(getPath());
	if (!file.is_open()) {
		return;
	}
	std::string content = "";
	std::string line;

	while (std::getline(file, line)) {
		content += line + "\n";
	}
	file.close();
	auto result = TodoMdFormat::parse(content);
	for (const auto &dayData : result.days) {
		Day *newDay = day(dayData.date);
		for (const auto &eventData : dayData.events) {
			Event *newEvent = newDay->createEvent(eventData);
			for (const auto &taskData : eventData.tasks) {
				TaskItem *newTask = newEvent->createTask(taskData);
			}
		}
		for (const auto &taskData : dayData.tasks) {
			TaskItem *newTask = newDay->createTask(taskData);
		}
	}
	setName(result.name);
};
} // namespace mirai
