package gui.menu;

import java.util.Stack;

import gui.widget.AnimatedBackground;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.flag.ImGuiKey;
import imgui.flag.ImGuiWindowFlags;

public class StateMachine {

	private final Stack<BaseView> menus;
	private final AnimatedBackground background;

	public StateMachine() {
		this.menus = new Stack<>();
		this.background = new AnimatedBackground();
	}

	public void clear() {
		for (BaseView view : menus) {
			view.cleanResources();
		}
		menus.clear();
	}

	public void pushState(BaseView menu) {
		menus.add(menu);
	}

	public void overrideState(BaseView menu) {
		menus.getLast().cleanResources();
		menus.set(menus.size() - 1, menu);
	}

	public void popState() {
		menus.getLast().cleanResources();
		menus.pop();
	}

	private void checkEscape() {
		if (ImGui.isKeyPressed(ImGuiKey.Escape) && menus.size() > 1) {
			menus.getLast().closeMenu();
		}
	}

	public void render() {
		var displaySize = ImGui.getIO().getDisplaySize();
		this.background.render();
		ImGui.setNextWindowPos(new ImVec2(0.0f, 0.0f));
		ImGui.setNextWindowSize(displaySize);
		ImGui.begin("##Main Window", null, ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoMove
				| ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoBackground);
		menus.get(menus.size() - 1).render();
		ImGui.end();
		// ImGui.showDemoWindow();
		checkEscape();
	}

}
