package de.winniepat.citrus.utils.text;

import io.wispforest.owo.ui.component.LabelComponent;
import io.wispforest.owo.ui.core.*;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.*;
import net.minecraft.util.math.MathHelper;

public class TextComponent extends LabelComponent {
    float scale = 1f;

    public TextComponent(Text text) {
        super(text);
    }

    public TextComponent scale(float scale) {
        this.scale = scale;
        this.notifyParentIfMounted();
        return this;
    }

    @Override
    protected int determineHorizontalContentSize(Sizing sizing) {
        return MathHelper.ceil(super.determineHorizontalContentSize(sizing) * this.scale);
    }

    @Override
    protected int determineVerticalContentSize(Sizing sizing) {
        return MathHelper.ceil(super.determineVerticalContentSize(sizing) * this.scale);
    }

    @Override
    public void draw(OwoUIDrawContext context, int mouseX, int mouseY, float partialTicks, float delta) {
        MatrixStack matrices = context.getMatrices();
        matrices.push();

        matrices.scale(this.scale, this.scale, this.scale);

        int baseScreenY = this.y;

        switch (this.verticalTextAlignment) {
            case CENTER -> baseScreenY += (this.height - this.textHeight()) / 2;
            case BOTTOM -> baseScreenY += this.height - this.textHeight();
        }

        int x = (int) (this.x / this.scale);
        int y = (int) (baseScreenY / this.scale);

        context.draw(() -> {
            int currenY = y;
            for (OrderedText renderText : this.wrappedText) {
                int renderX = x;

                switch (this.horizontalTextAlignment) {
                    case CENTER -> renderX = x + (int) (((this.width / this.scale) - this.textRenderer.getWidth(renderText)) / 2f);
                    case RIGHT -> renderX = x + (int) (this.width / this.scale - this.textRenderer.getWidth(renderText));
                }

                int renderY = currenY + (int) ((this.lineHeight() - 9) / this.scale);

                context.drawText(this.textRenderer, renderText, renderX, renderY, this.color.get().argb(),this.shadow);

                currenY += (int) ((this.lineHeight() + this.lineSpacing()) / this.scale);
            }
        });

        matrices.pop();
    }
}