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

import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.sections.EffSecSpawn;
import ch.njol.skript.util.Direction;
import ch.njol.util.Kleenean;
import com.github.shanebeee.skr.Registration;
import com.shanebeestudios.skbee.api.skript.base.Effect;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.FallingBlock;
import org.bukkit.event.Event;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class EffSpawnFallingBlockData extends Effect {

    public static void register(Registration reg) {
        reg.newEffect(EffSpawnFallingBlockData.class,
                "(skbee|le) spawn falling %blockdata% [%directions% %locations%]")
            .name("Spawn Falling BlockData")
            .description("Spawn a falling block data.",
                "This is a temp effect until Skript properly handles block data with spawning of falling blocks.")
            .examples("le spawn falling snow[layers=3] above target block of player")
            .since("2.10.0")
            .register();
    }

    private Expression<BlockData> blockData;
    private Expression<Location> locations;

    @SuppressWarnings("unchecked")
    @Override
    public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
        this.blockData = (Expression<BlockData>) exprs[0];
        this.locations = Direction.combine((Expression<? extends Direction>) exprs[1], (Expression<? extends Location>) exprs[2]);
        return true;
    }

    @Override
    protected void execute(Event event) {
        BlockData blockData = this.blockData.getSingle(event);
        if (blockData == null) {
            return;
        }

        for (Location location : this.locations.getArray(event)) {
            World world = location.getWorld();
            EffSecSpawn.lastSpawned = world.spawn(location, FallingBlock.class,
                entity -> entity.setBlockData(blockData));
        }
    }

    @Override
    public @NotNull String toString(@Nullable Event e, boolean d) {
        return "le spawn falling " + this.blockData.toString(e, d) + this.locations.toString(e, d);
    }

}
