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

import ch.njol.skript.entity.EntityData;
import ch.njol.skript.lang.Literal;
import ch.njol.skript.lang.SkriptEvent;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import com.github.shanebeee.skr.Registration;
import org.bukkit.block.Block;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.Entity;
import org.bukkit.event.Event;
import org.bukkit.event.entity.SpawnerSpawnEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class EvtSpawnerSpawn extends SkriptEvent {

    public static void register(Registration reg) {
        reg.newEvent(EvtSpawnerSpawn.class, SpawnerSpawnEvent.class,
                "spawner spawn[ing] [of %entitydatas%]")
            .name("Spawner Spawn")
            .description("Called whenever an entity is spawned via a spawner.")
            .examples("on spawner spawn of zombie:",
                "\treset spawner timer of event-block")
            .since("2.16.0")
            .register();

        reg.newEventValue(SpawnerSpawnEvent.class, Block.class)
            .converter(event -> {
                CreatureSpawner spawner = event.getSpawner();
                if (spawner != null) return spawner.getBlock();
                return null;
            })
            .register();
    }

    private Literal<EntityData<?>> spawnedEntities;

    @SuppressWarnings("unchecked")
    @Override
    public boolean init(Literal<?>[] literals, int matchedPattern, ParseResult parseResult) {
        this.spawnedEntities = (Literal<EntityData<?>>) literals[0];
        return true;
    }

    @Override
    public boolean check(Event event) {
        if (this.spawnedEntities == null) return true;
        if (event instanceof SpawnerSpawnEvent spawnerEvent) {
            Entity spawnedEntity = spawnerEvent.getEntity();

            return this.spawnedEntities.check(event, entityData -> entityData.isInstance(spawnedEntity));
        }
        return false;
    }

    @Override
    public @NotNull String toString(@Nullable Event e, boolean d) {
        return "spawner spawn" + (this.spawnedEntities != null ? " of " + this.spawnedEntities.toString(e, d) : "");
    }

}
