/*
 * 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 "Mirai.h"
#include "Config.h"
#include "TaskItem.h"
#include "cpp-utils/debug.h"
#include "utils.h"
#include <algorithm>
#include <iostream>
#include <memory>
#include <optional>
#include <ostream>
#include <vector>

namespace mirai
{

void Mirai::loadSource(std::unique_ptr<BaseSource> &&resource)
{
	resource->load();
	sources_.push_back(std::move(resource));
	reloadTags();
};

void Mirai::unloadAllSources()
{
	sources_.clear();
}

void Mirai::save()
{
	for (auto &resource : sources_) {
		if (resource->isDirty()) {
			resource->save();
			resource->setDirty(false);
		}
	}
	reloadTags();
}

void Mirai::deleteTask(const TaskItem &taskItem)
{
	for (auto &resource : sources_) {
		resource->deleteTask(taskItem);
	}
}

std::vector<std::unique_ptr<BaseSource>> &Mirai::getSources()
{
	return sources_;
}

std::optional<std::reference_wrapper<BaseSource>> Mirai::getSourceByName(const std::string &name)
{
	auto resourceIterator =
		std::ranges::find_if(sources_, [&](const std::unique_ptr<BaseSource> &resource) {
			return resource->getName() == name;
		});

	if (resourceIterator == sources_.end()) {
		return std::nullopt;
	}
	return *(resourceIterator->get());
}

const std::vector<std::string> &Mirai::getTags()
{
	return tags_;
}

void Mirai::reloadTags()
{
	// TODO TAGS
	/*cpputils::debug::Timer reloadingTagsDuration;*/
	/*tags.clear();*/
	/*for (auto &resource : resources) {*/
	/*for (auto &task : resource->getTasks()) {*/
	/*for (auto &tag : task->getTags()) {*/
	/*if (!vectorUtils::contains(tags, tag)) {*/
	/*tags.push_back(tag);*/
	/*}*/
	/*}*/
	/*}*/
	/*}*/
	/*reloadingTagsDuration.printTimeElapsed("ReloadingTags");*/
}

BaseSource *Mirai::getSourceById(int id)
{
	if (id >= sources_.size()) {
		return nullptr;
	}
	return sources_.at(id).get();
}

} // namespace mirai
