/*
 * 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 "Task.h"
#include "DataProvider.h"
#include "Day.h"
#include "utils.h"
#include <optional>
#include <string>

namespace mirai
{

int Task::id() const
{
	return task_.id;
}

int Task::sourceId() const
{
	return data_->id;
}

std::string Task::title() const
{
	return task_.title;
}

mirai::TaskState Task::state() const
{
	return task_.state;
}

bool Task::checked() const
{
	return task_.state == mirai::DONE;
}

bool Task::hasEvent() const
{
	return task_.eventId.has_value();
}

bool Task::hasDate() const
{
	return task_.dayId.has_value();
}

void Task::setTitle(const std::string &newTitle)
{
	data_->updateTask(id(), {.title = newTitle});
}

void Task::setDay(const Day &day)
{
	auto emptyEventId = std::optional<std::optional<int>>(std::optional<int>(std::nullopt));
	data_->updateTask(id(), {.dayId = day.id(), .eventId = emptyEventId});
}

void Task::setDate(const Date &date)
{
	auto day = data_->getDayByDate(date);
	if (!day.has_value()) {
		day = data_->insertDay({.id = generateUniqueId(), .date = date});
	}
	auto emptyEventId = std::optional<std::optional<int>>(std::optional<int>(std::nullopt));
	data_->updateTask(id(), {.dayId = day.value().id, .eventId = emptyEventId});
}

void Task::setEvent(const Event &event)
{
	auto emptyDayId = std::optional<std::optional<int>>(std::optional<int>(std::nullopt));
	data_->updateTask(id(), {.dayId = emptyDayId, .eventId = event.id()});
}

void Task::setChecked(bool checked)
{
	data_->updateTask(id(), {.state = checked ? DONE : TODO});
}

} // namespace mirai
