//
// Created by slinky on 5/7/26.
//

#include "Scene.h"

#include "Components.h"

Scene::Scene() {
    root = _registry.create();
    attach_component<Components::Transform>(root);
    attach_component<Components::Relationship>(root);
}

entt::entity Scene::create_game_object() {
    return create_game_object(root);
}

entt::entity Scene::create_game_object(entt::entity parent) {
    const entt::entity entity = _registry.create();
    attach_component<Components::Transform>(entity);
    attach_component<Components::Relationship>(entity);

    add_child(parent, entity);

    return entity;
}

template<typename T>
T& Scene::attach_component(entt::entity e) {
    return _registry.emplace<T>(e);
}

template<typename T>
T &Scene::attach_component(entt::entity e, T data) {
    return _registry.emplace<T>(e, data);
}

template<typename T>
T& Scene::fetch_component(entt::entity e) {
    return _registry.get<T>(e);
}

void Scene::add_child(entt::entity parent, entt::entity child) {
    auto& parentRelationship = fetch_component<Components::Relationship>(parent);

    if (parentRelationship.first_child == entt::null) {
        parentRelationship.first_child = child;
        return;
    }

    entt::entity lastSibling = parentRelationship.first_child;
    auto& lastSiblingRelationship = fetch_component<Components::Relationship>(lastSibling);
    while (lastSiblingRelationship.next_sibling != entt::null) {
        lastSibling = lastSiblingRelationship.next_sibling;
        lastSiblingRelationship = fetch_component<Components::Relationship>(lastSibling);
    }
    lastSiblingRelationship.next_sibling = child;

    auto& childRelationship = fetch_component<Components::Relationship>(child);
    childRelationship.prev_sibling = lastSibling;
    childRelationship.next_sibling = entt::null;
    childRelationship.parent = parent;
}
