/*
 * 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 "AddSourceWindow.h"
#include "../../SeleniteSetup.h"
#include "evalyte-cpp-common/evalyte.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>

AddSourceWindow::AddSourceWindow(mirai::Mirai *miraiInstance) : miraiInstance_(miraiInstance)
{
	window_->set_default_source_path(slint::SharedString(evalyte::dataDirectoryPath("mirai") + "/")
	);

	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 AddSourceWindow::setupCallbacks()
{
	window_->on_add_source([&](ui::AddSourceParam params) {
		std::unique_ptr<mirai::DataProvider> file =
			std::make_unique<mirai::MarkdownDataProvider>(std::string(params.path));
		miraiInstance_->addSource(
			std::string(params.name), std::string(params.type), std::move(file)
		);
		window_->hide();
	});
}

void AddSourceWindow::open()
{
	window_->show();
}

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