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

namespace frostbite2D {

Scene* Scene::current_ = nullptr;

Scene::Scene() {
  current_ = this;
}

Scene::~Scene() {
}

void Scene::onEnter() {
  SDL_Log("Scene  onEnter");
}

void Scene::onExit() {
  SDL_Log("Scene  onExit");
}

void Scene::Update(float deltaTime) {
  UpdateChildren(deltaTime);
}

void Scene::Render() {
  RenderChildren();
}

Scene* Scene::GetCurrent() {
  return current_;
}

bool Scene::OnEvent(const Event& event) {
  if (Actor::OnEvent(event)) {
    return true;
  }

  if (dispatchToChildren(event)) {
    return true;
  }

  return false;
}

bool Scene::dispatchToChildren(const Event& event) {
  if (event.isPropagationStopped()) {
    return false;
  }

  std::vector<Actor*> sortedChildren;
  for (auto it = children_.begin(); it != children_.end(); ++it) {
    Actor* child = it->Get();
    if (child && child->IsEventReceiveEnabled()) {
      sortedChildren.push_back(child);
    }
  }

  std::sort(sortedChildren.begin(), sortedChildren.end(),
    [](Actor* a, Actor* b) {
      return a->GetEventPriority() < b->GetEventPriority();
    });

  for (Actor* child : sortedChildren) {
    if (child->IsEventInterceptEnabled()) {
      if (child->OnEvent(event)) {
        return true;
      }
    } else {
      if (child->DispatchEvent(event)) {
        return true;
      }
    }
  }

  return false;
}

}

