#include "resources/resource_manager.hpp"

#include "resources/model.hpp"

#include <algorithm>
#include <array>
#include <cctype>
#include <filesystem>
#include <optional>
#include <string>
#include <string_view>

using namespace kuiper;

static constexpr std::array<std::string_view, 2> GLTF_FILE_EXTENSIONS {".gltf", ".glb"};

std::optional<resource_metadata> resource_manager::import_from_path(const std::filesystem::path& path) {
    if (!std::filesystem::exists(path) || !std::filesystem::is_regular_file(path)) {
        return std::nullopt;
    }

    std::string file_ext = path.extension().string();
    std::transform(file_ext.begin(), file_ext.end(), file_ext.begin(), [](const auto c) {
        return std::tolower(c);
    });

    const auto model_ext_it =
        std::find_if(GLTF_FILE_EXTENSIONS.begin(), GLTF_FILE_EXTENSIONS.end(), [&file_ext](const auto s) {
            return file_ext == s;
        });

    if (model_ext_it != GLTF_FILE_EXTENSIONS.end()) {
        auto maybe_model = resource::model::from_gltf_path(path);
        if (maybe_model)
            add<resource::model>(std::move(maybe_model.value()), path.relative_path().string());
    }

    return std::optional<resource_metadata>();
}
