package eu.mhsl.minenet.minigames.message.component;

import eu.mhsl.minenet.minigames.lang.Languages;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.format.NamedTextColor;
import net.minestom.server.entity.Player;
import org.apache.commons.text.WordUtils;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.List;

public class TranslatedComponent implements ComponentLike, Translatable {
    private final String mapId;
    private String result;

    private NamedTextColor color;
    private int wrap = 0;

    public static TranslatedComponent byId(String mapId) {
        return new TranslatedComponent(mapId);
    }

    public static Component assemble(String mapid, Player p) {
        return new TranslatedComponent(mapid).getAssembled(p);
    }

    private TranslatedComponent(String mapId) {
        this.mapId = mapId;
    }

    public void assemble(Player p) {
        result = Languages.getInstance().getLanguage(p).getEntry(mapId);
        if(wrap > 0) {
            result = WordUtils.wrap(result, wrap, "\n", false);
        }
    }

    public TranslatedComponent addWrap() {
        return this.addWrap(30);
    }
    public TranslatedComponent addWrap(int wrap) {
        this.wrap = wrap;
        return this;
    }

    public Component getAssembled(Player p) {
        this.assemble(p);
        return asComponent();
    }

    public List<Component> getWrappedAssembled(Player p) {
        this.assemble(p);
        return asWrappedComponent();
    }

    public TranslatedComponent setColor(NamedTextColor color) {
        this.color = color;
        return this;
    }

    @Override
    public @NotNull Component asComponent() {
        return this.componentFromString(result);
    }

    public List<Component> asWrappedComponent() {
        return Arrays.stream(result.split("\n")).map(this::componentFromString).toList();
    }

    private Component componentFromString(String data) {
        if(color != null)
            return Component.text(data, color);
        else
            return Component.text(data);
    }
}
