//
// Created by sebastian on 30.07.26.
//

#include "TextureImporter.h"

#include <stb_image.h>

engine::RawTextureData engine::TextureImporter::import(const std::filesystem::path &path, bool flipY) {
    stbi_set_flip_vertically_on_load(flipY);

    int width = 0;
    int height = 0;
    int channels = 0;

    stbi_uc* pixels = stbi_load(path.string().c_str(), &width, &height, &channels, 0);

    if (!pixels) {
        throw std::runtime_error(
            std::string("Failed to load texture: ")
            + path.string()
            + " ("
            + stbi_failure_reason()
            + ")");
    }

    RawTextureData data;
    data.name = path.stem().string();
    data.width = width;
    data.height = height;
    data.channels = channels;

    const auto size =
        static_cast<size_t>(width)
        * height
        * channels;

    data.pixels.assign(
        pixels,
        pixels + size);

    stbi_image_free(pixels);

    return data;
}
