#include <frostbite2D/scene/scene_manager.h>
#include <frostbite2D/scene/scene.h>
#include <SDL2/SDL.h>

namespace frostbite2D {

SceneManager& SceneManager::get() {
  static SceneManager instance;
  return instance;
}

// 移除析构函数中的自动销毁，改为在 Application::shutdown() 中手动调用

void SceneManager::PushScene(Ptr<Scene> scene) {
  if (!scene) {
    return;
  }

  if (!sceneStack_.empty()) {
    sceneStack_.back()->onExit();
  }

  sceneStack_.push_back(scene);
  scene->onEnter();
}

void SceneManager::PopScene() {
  if (sceneStack_.empty()) {
    return;
  }

  sceneStack_.back()->onExit();
  sceneStack_.pop_back();

  if (!sceneStack_.empty()) {
    sceneStack_.back()->onEnter();
  }
}

void SceneManager::ReplaceScene(Ptr<Scene> scene) {
  if (!scene) {
    return;
  }

  PopScene();
  PushScene(scene);
}

void SceneManager::ClearAll() {
  while (!sceneStack_.empty()) {
    sceneStack_.back()->onExit();
    sceneStack_.pop_back();
  }
}

void SceneManager::Update(float deltaTime) {
  if (!sceneStack_.empty()) {
    sceneStack_.back()->Update(deltaTime);
  }
}

void SceneManager::Render() {
  if (!sceneStack_.empty()) {
    sceneStack_.back()->Render();
  }
}

Scene* SceneManager::GetCurrentScene() const {
  if (sceneStack_.empty()) {
    return nullptr;
  }
  return sceneStack_.back().Get();
}

bool SceneManager::HasActiveScene() const {
  return !sceneStack_.empty();
}

}

