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

namespace mirai
{

Day::Day(BaseSource *source, const DayData &data) : source_(source), data_(data)
{
}

Event *Day::createEvent(const EventData &eventData)
{
	auto event = std::make_unique<Event>(source_, this, eventData);
	mirai::Event *eventPtr = event.get();
	events_.push_back(std::move(event));
	onChange();
	return eventPtr;
}

std::vector<std::unique_ptr<Event>> *Day::events()
{
	return &events_;
}

const Date &Day::getDate() const
{
	return data_.date;
}

TaskItem *Day::createTask(const TaskItemData &taskData)
{
	auto task = std::make_unique<TaskItem>(source_, this, taskData);
	mirai::TaskItem *taskPtr = task.get();
	tasks_.push_back(std::move(task));
	onChange();
	return taskPtr;
}

void Day::deleteTask(const TaskItem &taskToDelete)
{
	int id = taskToDelete.id();
	tasks_.erase(
		std::remove_if(
			tasks_.begin(), tasks_.end(),
			[&](const std::unique_ptr<TaskItem> &task) {
				return task->id() == id;
			}
		),
		tasks_.end()
	);
	onChange();
}

void Day::deleteEvent(const Event &eventToDelete)
{
	int id = eventToDelete.id();
	events_.erase(
		std::remove_if(
			events_.begin(), events_.end(),
			[&](const std::unique_ptr<Event> &event) {
				return event->id() == id;
			}
		),
		events_.end()
	);
	onChange();
}

void Day::onChange()
{
	source()->setDirty(true);
}

std::vector<std::unique_ptr<TaskItem>> *Day::tasks()
{
	return &tasks_;
}

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

BaseSource *Day::source()
{
	return source_;
}
} // namespace mirai
