/*
 * Copyright 2016 - 2024 Gary Talent (gary@drinkingtea.net). All rights reserved.
 */

#include <ctime>

#include <ox/logconn/logconn.hpp>
#include <ox/std/trace.hpp>
#include <ox/std/uuid.hpp>
#include <keel/media.hpp>
#include <turbine/turbine.hpp>

#include <studio/context.hpp>
#include <studioapp/studioapp.hpp>
#include "studioapp.hpp"

namespace studio {

class StudioUIDrawer: public turbine::gl::Drawer {
	private:
		StudioUI &m_ui;
	public:
		explicit StudioUIDrawer(StudioUI &ui) noexcept: m_ui(ui) {
		}
	protected:
		void draw(turbine::Context&) noexcept final {
			m_ui.draw();
		}
};

static int updateHandler(turbine::Context &ctx) noexcept {
	auto sctx = turbine::applicationData<studio::StudioContext>(ctx);
	sctx->ui->update();
	return 16;
}

static void keyEventHandler(turbine::Context &ctx, turbine::Key key, bool down) noexcept {
	auto sctx = turbine::applicationData<studio::StudioContext>(ctx);
	sctx->ui->handleKeyEvent(key, down);
}

static ox::Error runApp(
		ox::CRStringView appName,
		ox::CRStringView projectDataDir,
		ox::UPtr<ox::FileSystem> &&fs) noexcept {
	oxRequireM(ctx, turbine::init(std::move(fs), appName));
	turbine::setWindowTitle(*ctx, keelCtx(*ctx).appName);
	turbine::setUpdateHandler(*ctx, updateHandler);
	turbine::setKeyEventHandler(*ctx, keyEventHandler);
	turbine::setConstantRefresh(*ctx, false);
	studio::StudioContext studioCtx;
	turbine::setApplicationData(*ctx, &studioCtx);
	StudioUI ui(*ctx, projectDataDir);
	studioCtx.ui = &ui;
	StudioUIDrawer drawer(ui);
	turbine::gl::addDrawer(*ctx, &drawer);
	auto const err = turbine::run(*ctx);
	turbine::gl::removeDrawer(*ctx, &drawer);
	return err;
}

ox::Error run(
		ox::CRStringView appName,
		ox::CRStringView projectDataDir,
		int,
		char const**) {
	// seed UUID generator
	auto const time = std::time(nullptr);
	ox::UUID::seedGenerator({
		static_cast<uint64_t>(time),
		static_cast<uint64_t>(time << 1)
	});
	// run app
	auto const err = runApp(appName, projectDataDir, ox::UniquePtr<ox::FileSystem>(nullptr));
	oxAssert(err, "Something went wrong...");
	return err;
}

}

namespace olympic {

ox::Error run(
		ox::StringView project,
		ox::StringView appName,
		ox::StringView projectDataDir,
		int argc,
		char const**argv) noexcept {
	return studio::run(ox::sfmt("{} {}", project, appName), projectDataDir, argc, argv);
}

}
