#include "Skybox.h"

Skybox::Skybox()
{
}

Skybox::~Skybox()
{
    for (auto& texture : textures)
    {
        if (texture)
        {
            texture->Release();
            texture = nullptr;
        }
    }
    textures.clear();
    translations.clear();
}

void Skybox::Initialize(d_3d_class* d3dClassRef)
{
    m_d3dClassRef = d3dClassRef;
}

object* Skybox::ConstructSkybox(application_class* app)
{
    Logger::Get().Log("Construct skybox", __FILE__, __LINE__, Logger::LogLevel::Initialize);

    char modelFilename[128];
    strcpy_s(modelFilename, "assets/Model/OBJ/skysphere.obj");
    
    std::vector<std::wstring> skyboxTextures = {
        L"assets/Skybox/skybox.png",
    };

    TextureContainer SkyboxTextures;

    // Load the textures
    for (const auto& textureFilename : skyboxTextures)
    {
        ID3D11ShaderResourceView* texture = nullptr;
        HRESULT result = DirectX::CreateWICTextureFromFile(m_d3dClassRef->get_device(), m_d3dClassRef->get_device_context(), textureFilename.c_str(), nullptr, &texture);
        if (FAILED(result))
        {
            Logger::Get().Log("Failed to load texture: " + std::string(textureFilename.begin(), textureFilename.end()), __FILE__, __LINE__, Logger::LogLevel::Error);
            return nullptr;
        }
        SkyboxTextures.diffuse.push_back(texture);
        
    }

    // Create the model object
    m_Skybox = new object(*app);
    HRESULT result = m_Skybox->Initialize(m_d3dClassRef->get_device(), m_d3dClassRef->get_device_context(), modelFilename, SkyboxTextures);
    if (!result)
    {
        Logger::Get().Log("Could not initialize the skybox model object", __FILE__, __LINE__, Logger::LogLevel::Error);
        delete m_Skybox;
        return nullptr;
    }
    m_Skybox->SetTranslateMatrix(XMMatrixTranslation(0.0f, 0.0f, 0.0f)); // Set the initial translation of the skybox
    m_Skybox->SetActiveShader(ShaderType::SKYBOX);
    
    return m_Skybox; // Return the constructed skybox object
}