package land.chipmunk.chipmunkmod.config.migrations;

import land.chipmunk.chipmunkmod.config.migration.ConfigMigration;
import land.chipmunk.chipmunkmod.util.configurate.ConfigurateUtilities;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.SelectorComponent;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.renderer.TranslatableComponentRenderer;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.configurate.transformation.ConfigurationTransformation;

import java.util.List;

import static org.spongepowered.configurate.NodePath.path;

public final class MigrationV1 implements ConfigMigration {
    @Override
    public int version () {
        return 1;
    }

    @Override
    public ConfigurationTransformation create () {
        return ConfigurationTransformation.builder()
                .addAction(path("customChat", "format"),
                           ConfigurateUtilities.componentTransformer(new CustomChatFormatMigrator(), null))
                .build();
    }

    private static final class CustomChatFormatMigrator extends TranslatableComponentRenderer<Void> {
        @Override
        protected @NotNull Component renderSelector (final @NotNull SelectorComponent component,
                                                     final @NotNull Void context) {
            final String pattern = component.pattern();
            if (pattern.equals("USERNAME") || pattern.equals("UUID")) {
                final SelectorComponent.Builder builder = Component.selector()
                        .pattern("@s");

                return this.mergeStyleAndOptionallyDeepRender(component, builder, context);
            }

            return super.renderSelector(component, context);
        }

        // Older configs had things like: `{ "text": "", "extra": ["MESSAGE"] }`
        // We don't need that anymore, transform it to `{ "text": "MESSAGE" }`
        @Override
        protected @NotNull Component renderText (@NotNull final TextComponent component, @NotNull final Void context) {
            if (!component.content().isEmpty() || component.children().size() != 1) {
                return super.renderText(component, context);
            }

            final Component onlyChild = component.children().getFirst();
            if (!onlyChild.equals(Component.text("MESSAGE"))) {
                return super.renderText(component, context);
            }

            final Component newComponent = component
                    .children(List.of()); // Clear children
            final TextComponent.Builder builder = Component.text()
                    .content("MESSAGE");

            return this.mergeStyleAndOptionallyDeepRender(newComponent, builder, context);
        }
    }
}
