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

#pragma once

#include <ox/model/def.hpp>
#include <ox/std/vec.hpp>

#include <glutils/glutils.hpp>
#include <studio/editor.hpp>

#include "tilesheetpixelgrid.hpp"
#include "tilesheetpixels.hpp"
#include "tilesheeteditorview.hpp"

namespace nostalgia::core {

enum class Tool {
	None,
	Draw,
	Fill,
	Select,
};

class TileSheetEditorImGui: public studio::Editor {

	private:
		class SubSheetEditor {
			private:
				ox::BString<100> m_name;
				int m_cols = 0;
				int m_rows = 0;
				bool m_show = false;
			public:
				ox::Signal<ox::Error(ox::StringView const&name, int cols, int rows)> inputSubmitted;
				constexpr void show(ox::StringView const&name, int cols, int rows) noexcept {
					m_show = true;
					m_name = name;
					m_cols = cols;
					m_rows = rows;
				}
				void draw(turbine::Context &sctx) noexcept;
				void close() noexcept;
				[[nodiscard]]
				inline bool isOpen() const noexcept { return m_show; }
		};
		class ExportMenu {
			private:
				 int m_scale = 0;
				 bool m_show = false;
			public:
				ox::Signal<ox::Error(int scale)> inputSubmitted;
				constexpr void show() noexcept {
					m_show = true;
					m_scale = 5;
				}
				void draw(studio::StudioContext &sctx) noexcept;
				void close() noexcept;
				[[nodiscard]]
				inline bool isOpen() const noexcept { return m_show; }
		};
		std::size_t m_selectedPaletteIdx = 0;
		studio::StudioContext &m_sctx;
		turbine::Context &m_tctx;
		ox::Vector<ox::String> m_paletteList;
		SubSheetEditor m_subsheetEditor;
		ExportMenu m_exportMenu;
		glutils::FrameBuffer m_framebuffer;
		TileSheetEditorView m_view;
		TileSheetEditorModel &m_model;
		float m_palViewWidth = 300;
		ox::Vec2 m_prevMouseDownPos;
		Tool m_tool = Tool::Draw;

	public:
		TileSheetEditorImGui(studio::StudioContext &sctx, ox::CRStringView path);

		~TileSheetEditorImGui() override = default;

		void exportFile() override;

		void cut() override;

		void copy() override;

		void paste() override;

		void keyStateChanged(turbine::Key key, bool down) override;

		void draw(studio::StudioContext&) noexcept override;

		void drawSubsheetSelector(TileSheet::SubSheet&, TileSheet::SubSheetIdx &path);

		[[nodiscard]]
		static ox::Vec2 clickPos(ImVec2 const&winPos, ox::Vec2 clickPos) noexcept;

	protected:
		ox::Error saveItem() noexcept override;

	private:
		void showSubsheetEditor() noexcept;

		ox::Error exportSubhseetToPng(int scale) noexcept;

		void drawTileSheet(ox::Vec2 const&fbSize) noexcept;

		void drawPaletteSelector() noexcept;

		ox::Error updateActiveSubsheet(ox::StringView const&name, int cols, int rows) noexcept;

		ox::Error setPaletteSelection() noexcept;

	// slots
	private:
		ox::Error markUnsavedChanges(studio::UndoCommand const*) noexcept;

};

}
