package com.shanebeestudios.skbee.elements.worldgen.effects;

import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.Kleenean;
import com.github.shanebeee.skr.Registration;
import com.shanebeestudios.skbee.api.skript.base.Effect;
import com.shanebeestudios.skbee.api.worldgen.BeeWorldCreator;
import com.shanebeestudios.skbee.api.worldgen.ChunkGenManager;
import com.shanebeestudios.skbee.api.worldgen.CustomChunkGenerator;
import org.bukkit.event.Event;
import org.jetbrains.annotations.NotNull;

public class EffWorldCreatorSetGenerator extends Effect {

    public static void register(Registration reg) {
        reg.newEffect(EffWorldCreatorSetGenerator.class,
                "set chunk generator of %worldcreator% to chunk generator with id %string%")
            .name("ChunkGenerator - WorldCreator Generator")
            .description("Set the chunk generator of a world creator.")
            .examples("on load:",
                "\tif world \"mars\" is not loaded:",
                "\t\tset {_w} to world creator named \"mars\"",
                "\t\tset chunk generator of {_w} to chunk generator with id \"mars\"",
                "\t\tload world from creator {_w}")
            .since("3.5.0")
            .register();
    }

    private Expression<BeeWorldCreator> worldCreator;
    private Expression<String> id;

    @SuppressWarnings("unchecked")
    @Override
    public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
        this.worldCreator = (Expression<BeeWorldCreator>) exprs[0];
        this.id = (Expression<String>) exprs[1];
        return true;
    }

    @Override
    protected void execute(@NotNull Event event) {
        BeeWorldCreator worldCreator = this.worldCreator.getSingle(event);
        String id = this.id.getSingle(event);
        if (worldCreator == null) {
            error("Invalid world creator: " + this.worldCreator.toString(event, true));
            return;
        }
        if (id == null) {
            error("Invalid id: " + this.id.toString(event, true));
            return;
        }

        CustomChunkGenerator customChunkGenerator = ChunkGenManager.getByID(id);
        if (customChunkGenerator == null) {
            error("Invalid generator: " + id);
            return;
        }
        worldCreator.setChunkGenerator(customChunkGenerator);
    }

    @Override
    public @NotNull String toString(Event e, boolean d) {
        String creator = this.worldCreator.toString(e, d);
        String id = this.id.toString(e, d);
        return "set chunk generator of " + creator + " to chunk generator with id " + id;
    }

}
