#include <frostbite2D/2d/actor.h>
#include <SDL2/SDL.h>

namespace frostbite2D {

Actor::Actor()
  : parent_(nullptr)
  , scene_(nullptr)
  , rotation_(0.0f)
  , visible_(true)
  , zOrder_(0)
  , opacity_(1.0f) {
}

Actor::~Actor() {
  RemoveAllChildren();
}

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

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

void Actor::AddChild(Ptr<Actor> child) {
  if (!child) {
    return;
  }

  if (child->GetParent() == this) {
    return;
  }

  if (child->GetParent()) {
    child->GetParent()->RemoveChild(child);
  }

  child->SetParent(this);
  child->SetScene(scene_);
  children_.PushBack(child);
}

void Actor::RemoveChild(Ptr<Actor> child) {
  if (!child || child->GetParent() != this) {
    return;
  }

  child->SetParent(nullptr);
  child->SetScene(nullptr);
  children_.Remove(child);
}

void Actor::RemoveAllChildren() {
  while (!children_.IsEmpty()) {
    Ptr<Actor> child = children_.GetFirst();
    RemoveChild(child);
  }
}

void Actor::UpdateChildren(float deltaTime) {
  for (auto it = children_.begin(); it != children_.end(); ++it) {
    if (*it && (*it)->IsVisible()) {
      (*it)->Update(deltaTime);
    }
  }
}

void Actor::RenderChildren() {
  for (auto it = children_.begin(); it != children_.end(); ++it) {
    if (*it && (*it)->IsVisible()) {
      (*it)->Render();
    }
  }
}

}

