/*
 * 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 "EditSourceWindow.h"
#include "../../SeleniteSetup.h"
#include "mirai-core/MarkdownDataProvider.h"
#include "mirai-core/Mirai.h"
#include "slint.h"
#include "slint_string.h"
#include "ui.h"
#include <bits/chrono.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <optional>
#include <print>
#include <string>

EditSourceWindow::EditSourceWindow(mirai::Mirai *miraiInstance) : miraiInstance_(miraiInstance)
{

	const auto palettePath = std::string(getenv("HOME")) + "/.config/evalyte/theme.json";
	const auto palette = selenite::parseJson(palettePath);

	if (palette.has_value()) {
		setSelenitePalette(window_->global<ui::Palette>(), palette.value());
	}

	setupCallbacks();
}

void EditSourceWindow::setupCallbacks()
{
	window_->on_modify_source([&](ui::ModifySourceParam params) {
		miraiInstance_->editSource(params.id, std::string(params.name), std::string(params.path));
		close();
	});
	window_->on_delete_source([&](int sourceId) {
		miraiInstance_->deleteSource(sourceId);
		close();
	});
}

void EditSourceWindow::open(mirai::Source *source)
{
	assert(source != nullptr);
	auto markdownSource = dynamic_cast<mirai::MarkdownDataProvider *>(source->dataProvider());
	window_->set_id(source->id);
	window_->set_name(slint::SharedString(source->name()));
	window_->set_path(slint::SharedString(markdownSource->path()));
	window_->show();
}

void EditSourceWindow::close()
{
	window_->hide();
}
