mirai/src/core/TasksFile.cpp

72 lines
2.1 KiB
C++
Raw Normal View History

2024-04-10 16:53:18 +02:00
/*
* 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 "TasksFile.h"
#include "using.h"
namespace mirai {
TasksFile::TasksFile(TasksFileConstructor params) : name(params.name), path(params.path) {
for (const auto& task : params.tasks) {
processTaskMetaData(task);
tasks.push_back(std::make_unique<TaskItem>(task));
}
sortByDate();
}
const std::string& TasksFile::getName() const { return name; }
const std::string& TasksFile::getPath() const { return path; }
TasksPtrs& TasksFile::getTasks() { return tasks; }
Tags& TasksFile::getTags() { return tags; }
void TasksFile::addTask(std::string text, std::string date) {
auto newTask = std::make_unique<TaskItem>(TaskItem{
.text = text,
.state = TODO,
.date = date == "" ? "No date" : date
});
tasks.push_back(std::move(newTask));
sortByDate();
}
void TasksFile::removeTask(const TaskItem* taskToRemove) {
tasks.erase(std::remove_if(tasks.begin(), tasks.end(), [&] (const std::unique_ptr<TaskItem>& taskInFilter){
return taskInFilter.get() == taskToRemove;
}));
}
void TasksFile::processTaskMetaData(const TaskItem& task) {
const std::string metaDataSeparator = " -- ";
auto separatorIndex = task.text.find(metaDataSeparator);
if (separatorIndex == std::string::npos) {
return;
}
auto metaData = task.text.substr(separatorIndex + metaDataSeparator.length());
std::regex regex("(#[a-zA-Z0-1]+)");
std::smatch matches;
while (std::regex_search(metaData, matches, regex))
{
if (std::find(tags.begin(), tags.end(), matches[0]) == tags.end()) {
tags.push_back(matches[0]);
}
metaData = matches.suffix();
}
}
void TasksFile::sortByDate() {
std::sort(tasks.begin(), tasks.end(), [] (const std::unique_ptr<TaskItem>& t1, const std::unique_ptr<TaskItem>& t2) {
if (t1->hasDate() && !t2->hasDate()) {
return true;
} else if (!t1->hasDate() && t2->hasDate()) {
return false;
}
return t1->date < t2->date;
});
}
}