//
// Created by sebastian on 09.02.26.
//

#include "UILayer.h"

#include "../engine/core/gui/text/Font.h"
#include "../engine/core/gui/uiComponent/UiImage.h"
#include "../engine/core/gui/uiComponent/UiText.h"
#include "../engine/renderer/loader/Loader.h"
#include "../engine/renderer/model/GUITexture.h"

UILayer::UILayer() {
    Loader& loader = Loader::instance();
    guiRenderer = std::make_unique<GUIRenderer>(loader);
    textRenderer = std::make_unique<TextRenderer>();
}

void UILayer::onAttach() {
    Layer::onAttach();



    rootContainer = std::make_unique<UiContainer>();
    LayoutStyle& rootLayout = rootContainer->getLayoutStyle();
    rootLayout.justifyContent = JustifyContent::End;

    auto imageStyle = LayoutStyle();
    imageStyle.width = SizeValue(0.25f, SizeUnit::Percent);
    imageStyle.height = SizeValue(0.25f, SizeUnit::Percent);
    imageStyle.margin.left   = {50.f, SizeUnit::Pixels}; // 50px
    imageStyle.margin.top    = {0.f, SizeUnit::Percent};

    auto image = std::make_unique<UiImage>(
        Loader::instance().loadTextureFromFile("assets/textures/texture.png").getTextureID(),
        imageStyle
    );

    auto image2 = std::make_unique<UiImage>(
        Loader::instance().loadTextureFromFile("assets/textures/texture.png").getTextureID(),
        imageStyle
    );

    auto image3 = std::make_unique<UiImage>(
    Loader::instance().loadTextureFromFile("assets/textures/texture.png").getTextureID(),
    imageStyle
);
    rootContainer->addChild(std::move(image));
    rootContainer->addChild(std::move(image2));
    //rootContainer->addChild(std::move(image3));



    Font myFont("/usr/share/fonts/TTF/DejaVuSans.ttf", 48);
    font = std::make_unique<Font>(myFont);
    //auto text = std::make_unique<UiText>(*font, "Hello World!", glm::vec2(0.5f, 0.5f),  glm::vec3(1,1,1));

    auto text = std::make_unique<UiText>(*font, "Hello World", imageStyle);

    rootContainer->addChild(std::move(text));
}

void UILayer::onUpdate() {
    Layer::onUpdate();
    Dimensions rootParent {0.0, 0.0, 1.0, 1.0f};
    rootContainer->uiPositioner.compute(rootParent);

    UiRenderBundle renderBundle;
    if (rootContainer) {
        rootContainer->collectRenderData(renderBundle);
    }

    auto guis = renderBundle.getGUITextures();
    guiRenderer->render(guis);

    auto texts = renderBundle.getTexts();

    textRenderer->renderTexts(texts);

}

void UILayer::onDetach() {
    Layer::onDetach();
}
