#pragma once

#include <frostbite2D/base/RefObject.h>
#include <frostbite2D/types/type_alias.h>
#include <frostbite2D/types/type_math.h>
#include <frostbite2D/utils/intrusive_list.hpp>
#include <string>
#include <vector>

namespace frostbite2D {

class Actor;
class Scene;

using ActorList = IntrusiveList<RefPtr<Actor>>;

class Actor : public RefObject, protected IntrusiveListValue<RefPtr<Actor>> {
public:
  using IntrusiveListValue<RefPtr<Actor>>::GetNext;
  using IntrusiveListValue<RefPtr<Actor>>::GetPrev;

  Actor();
  virtual ~Actor();

  virtual void Update(float deltaTime);
  virtual void Render();

  void AddChild(RefPtr<Actor> child);
  void RemoveChild(RefPtr<Actor> child);
  void RemoveAllChildren();

  Actor* GetParent() const { return parent_; }
  Scene* GetScene() const { return scene_; }

  const std::string& GetName() const { return name_; }
  void SetName(const std::string& name) { name_ = name; }

  const Vec2& GetPosition() const { return position_; }
  void SetPosition(const Vec2& pos);
  void SetPosition(float x, float y);

  float GetRotation() const { return rotation_; }
  void SetRotation(float rotation);

  const Vec2& GetScale() const { return scale_; }
  void SetScale(const Vec2& scale);
  void SetScale(float scale);

  const Transform2D& GetLocalTransform() const;
  const Transform2D& GetWorldTransform() const;

  const Vec2& GetSize() const { return size_; }
  void SetSize(const Vec2& size);
  void SetSize(float width, float height);

  const Vec2& GetAnchor() const { return anchor_; }
  void SetAnchor(const Vec2& anchor);
  void SetAnchor(float x, float y);

  bool IsVisible() const { return visible_; }
  void SetVisible(bool visible) { visible_ = visible; }

  int GetZOrder() const { return zOrder_; }
  void SetZOrder(int zOrder);

  float GetOpacity() const { return opacity_; }
  void SetOpacity(float opacity);
  float GetWorldOpacity() const;

  ActorList& GetChildren() { return children_; }
  const ActorList& GetChildren() const { return children_; }

protected:
  void SetParent(Actor* parent) { parent_ = parent; }
  void SetScene(Scene* scene) { scene_ = scene; }

  void insertChildByZOrder(RefPtr<Actor> child);
  void UpdateChildren(float deltaTime);
  void RenderChildren();

  virtual void OnTransformChanged() {};

private:
  Actor* parent_;
  Scene* scene_;
  ActorList children_;

  std::string name_;
  Vec2 position_;
  float rotation_;
  Vec2 scale_ = Vec2(1.0f, 1.0f);
  Vec2 size_;
  Vec2 anchor_;
  bool visible_;
  int zOrder_;
  float opacity_;

  mutable Transform2D localTransform_;
  mutable Transform2D worldTransform_;
  mutable bool transformDirty_ = true;

  void markTransformDirty();
  void updateLocalTransform() const;
  void updateWorldTransform() const;

  friend class Scene;
};

}

