/*
 * 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 "BaseSource.h"
#include "Day.h"
#include "TaskItem.h"
#include <algorithm>
#include <functional>
#include <iostream>
#include <memory>
#include <ostream>

namespace mirai
{

void BaseSource::setDirty(bool shouldBeDirty)
{
	isDirty_ = shouldBeDirty;
}

bool BaseSource::isDirty() const
{
	return isDirty_;
}

Day *BaseSource::day(const Date &date)
{
	auto dayFound = std::find_if(days_.begin(), days_.end(), [&](std::unique_ptr<Day> &day) {
		return day->getDate().day == date.day && day->getDate().month == date.month &&
			   day->getDate().year == date.year;
	});
	if (dayFound == days_.end()) {
		auto newDay = std::make_unique<Day>(this, DayData{.date = date});
		Day *dayPtr = newDay.get();
		days_.push_back(std::move(newDay));
		return dayPtr;
	}
	return dayFound->get();
}

std::vector<std::unique_ptr<Day>> *BaseSource::days()
{
	return &days_;
}

void BaseSource::addDay(const DayData &dayData)
{
	days_.push_back(std::make_unique<Day>(this, dayData));
	setDirty(true);
}

TaskItem *BaseSource::getTaskById(int taskId)
{
	for (auto &day : days_) {
		for (auto &task : *day->tasks()) {
			if (task->id() == taskId) {
				return task.get();
			}
		}
		for (auto &event : *day->events()) {
			for (auto &task : *event->tasks()) {
				if (task->id() == taskId) {
					return task.get();
				}
			}
		}
	}
	return nullptr;
}

void BaseSource::deleteTask(const TaskItem &taskToDelete)
{
	for (auto &day : days_) {
		for (auto &task : *day->tasks()) {
			if (task->id() == taskToDelete.id()) {
				day->deleteTask(taskToDelete);
				return;
			}
		}
		for (auto &event : *day->events()) {
			for (auto &task : *event->tasks()) {
				if (task->id() == taskToDelete.id()) {
					event->deleteTask(taskToDelete);
					return;
				}
			}
		}
	}
}

Event *BaseSource::getEventById(int eventId)
{
	for (auto &day : days_) {
		for (auto &event : *day->events()) {
			if (event->id() == eventId) {
				return event.get();
			}
		}
	}
	return nullptr;
}

void BaseSource::setName(std::string name)
{
	this->name_ = name;
}

const std::string &BaseSource::getName() const
{
	return name_;
}

int BaseSource::id() const
{
	return id_;
}

/*void BaseResource::addTask(TaskItemData taskItem)*/
/*{*/
/*tasks.push_back(std::make_unique<TaskItem>(this, taskItem));*/
/*setDirty(true);*/
/*}*/

/*void BaseResource::removeTask(const TaskItem *taskToRemove)*/
/*{*/
/*auto findFunction = [&](const std::unique_ptr<TaskItem> &taskInFilter) {*/
/*return taskInFilter.get() == taskToRemove;*/
/*};*/
/*auto taskToDelete = std::remove_if(tasks_.begin(), tasks_.end(), findFunction);*/
/*if (taskToDelete == tasks_.end()) {*/
/*return;*/
/*}*/
/*tasks_.erase(taskToDelete);*/
/*setDirty(true);*/
/*}*/

int BaseSource::nextId_ = 0;

} // namespace mirai
