#include "pw/scene/scene.hpp"
#include "pw/scene/entity.hpp"

#include "pw/core/debug.hpp"
#include "pw/core/serialize.hpp"

#include "pw/core/geometry.hpp"
#include "pw/core/matrix_transform.hpp"

namespace pw {


struct mesh {
    geometry geom;
};

struct renderer {
    std::unique_ptr<int> state;
//    std::vector<matrials> mat;
};



scene::scene()
    : _registry{ std::make_shared<entt::registry>()}
{
}

// size_t scene::count_all_enties() const
// {
// size_t scene::count_alive_enties() const
// {
//     return _registry->storage().alive();
// }

void scene::update_transforms()
{


    //auto [t,r] = view.get<transform,parent>(entity);

#if 1

    // search for nodes with parent and transform (only find leaf nodes)
    auto view = _registry->view<transform,parent>(entt::exclude<children>);

    for (auto entity : view)
    {
        debug::d() << "info for entity " << (int)entity;

        // collect node path
        std::vector<transform> path;
        while (_registry->any_of<parent>(entity)) {
            if (_registry->any_of<transform>(entity)) {
                path.push_back(_registry->get<transform>(entity));
            }
            //
            entity = _registry->get<parent>(entity).entity;
        }

        debug::d() << "\tpath length " << path.size();
        std::reverse(path.begin(),path.end());

        auto m = pw::matrix4x4::identity();

        for (auto& transform : path) {

            transform._global = transform._local * m;
            m = transform._global;

            debug::d() << pw::serialize::matrix(m);
        }

        //        r = _registry->view<relationship>
    }






#else

    //    auto view = _registry->view<relationship>();

    //    for (auto e : view) {

    //        const auto& r = view.get<relationship>(e);

    //        if (r.children.size() && r.parent == entt::null) {
    //            debug::d() << "root '" << (int)e << "'";
    //        }

    ////        debug::d() << __PRETTY_FUNCTION__ << " " << view.get<relationship>(e).children.size();

    ////        if
    //    }
#endif

    //    auto vr = _registry->view<relationship>();

    //    for (auto [rel] : vr) {

    //    }

}




}
