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

#include <imgui.h>

#include <keel/media.hpp>

#include "sceneeditor-imgui.hpp"

namespace nostalgia::scene {

SceneEditorImGui::SceneEditorImGui(turbine::Context &ctx, ox::StringView path):
	Editor(path),
	m_ctx(ctx),
	m_editor(m_ctx, path),
	m_view(m_ctx, m_editor.scene()) {
	setRequiresConstantRefresh(false);
}

void SceneEditorImGui::draw(turbine::Context&) noexcept {
	auto const paneSize = ImGui::GetContentRegionAvail();
	m_view.draw(ox::Size{static_cast<int>(paneSize.x), static_cast<int>(paneSize.y)});
	auto &fb = m_view.framebuffer();
	auto const srcH = static_cast<float>(fb.height) / static_cast<float>(fb.width);
	auto const dstH = paneSize.y / paneSize.x;
	float xScale{}, yScale{};
	if (dstH > srcH) {
		// crop off width
		xScale = srcH / dstH;
		yScale = 1;
	} else {
		auto const srcW = static_cast<float>(fb.width) / static_cast<float>(fb.height);
		auto const dstW = (paneSize.x / paneSize.y);
		xScale = 1;
		yScale = srcW / dstW;
	}
	uintptr_t const buffId = fb.color.id;
	ImGui::Image(
		std::bit_cast<void*>(buffId),
		paneSize,
		ImVec2(0, 1),
		ImVec2(xScale, 1 - yScale));
}

void SceneEditorImGui::onActivated() noexcept {
	oxLogError(m_view.setupScene());
}

ox::Error SceneEditorImGui::saveItem() noexcept {
	const auto sctx = applicationData<studio::StudioContext>(m_ctx);
	oxReturnError(sctx->project->writeObj(itemPath(), m_editor.scene()));
	oxReturnError(keelCtx(m_ctx).assetManager.setAsset(itemPath(), m_editor.scene()));
	return {};
}

}
