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

import ch.njol.skript.lang.Literal;
import ch.njol.skript.lang.SkriptEvent;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.coll.CollectionUtils;
import com.github.shanebeee.skr.Registration;
import org.bukkit.entity.Entity;
import org.bukkit.event.Event;
import org.bukkit.event.world.EntitiesLoadEvent;
import org.bukkit.event.world.EntitiesUnloadEvent;
import org.jetbrains.annotations.NotNull;

public class EvtEntitiesLoad extends SkriptEvent {

    public static void register(Registration reg) {
        reg.newEvent(EvtEntitiesLoad.class,
                CollectionUtils.array(EntitiesLoadEvent.class, EntitiesUnloadEvent.class),
                "entities [:un]load[ed]")
            .name("Entities Loading")
            .description("Called when entities are loaded/unloaded.")
            .examples("on entities loaded:",
                "\tif event-entities is set:",
                "\t\tdelete event-entities",
                "\t\tbroadcast \"REMOVED ENTITIES!\"")
            .since("3.5.0")
            .register();

        reg.newEventValue(EntitiesLoadEvent.class, Entity[].class)
            .description("The entities that were loaded.")
            .converter(event -> event.getEntities().toArray(new Entity[0]))
            .register();
        reg.newEventValue(EntitiesUnloadEvent.class, Entity[].class)
            .description("The entities that were unloaded.")
            .converter(event -> event.getEntities().toArray(new Entity[0]))
            .register();
    }

    private boolean load;

    @Override
    public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult) {
        this.load = !parseResult.hasTag("un");
        return true;
    }

    @Override
    public boolean check(Event event) {
        if (this.load && event instanceof EntitiesLoadEvent) return true;
        else return !this.load && event instanceof EntitiesUnloadEvent;
    }

    @Override
    public @NotNull String toString(Event e, boolean d) {
        String load = this.load ? "loaded" : "unloaded";
        return "entities " + load;
    }

}
