package com.elmakers.mine.bukkit.integration.skript;

import ch.njol.skript.Skript;
import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Examples;
import ch.njol.skript.doc.Name;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.util.Direction;
import ch.njol.util.Kleenean;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.magic.MagicPlugin;
import org.bukkit.Location;
import org.bukkit.event.Event;

@Name("Spawn Magic Mob")
@Description("Spawn a magic mob.")
@Examples({"spawn 3 \"warlock\" at the targeted block", "spawn a \"mutant\" 5 meters above the player"})
public class EffSpawn extends Effect {
	private Expression<Location> locations;
	private Expression<String> mobKeys;
	private Expression<Number> amount;

    public static void register() {
        Skript.registerEffect(EffSpawn.class,
            "spawn [a] %strings% [%directions% %locations%]",
            "spawn %number% of %strings% [%directions% %locations%]");
    }

    @Override
    protected void execute(Event event) {
		final Number count = amount != null ? amount.getSingle(event) : 1;
		if (count == null)
			return;
		MageController controller = MagicPlugin.getAPI().getController();
		final String[] keys = mobKeys.getArray(event);
		for (final Location location : locations.getArray(event)) {
			for (final String mobKey : keys) {
				for (int i = 0; i < count.doubleValue(); i++) {
					controller.spawnMob(mobKey, location);
				}
			}
		}
    }

    @Override
    public String toString(Event event, boolean debug) {
        return "spawn " + (amount != null ? amount.toString(event, debug) + " " : "") + mobKeys.toString(event, debug) + " " + locations.toString(event, debug);
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) {
        amount = matchedPattern == 0 ? null : (Expression<Number>) (exprs[0]);
		mobKeys = (Expression<String>) exprs[matchedPattern];
		locations = Direction.combine((Expression<? extends Direction>) exprs[1 + matchedPattern], (Expression<? extends Location>) exprs[2 + matchedPattern]);
		return true;
    }
}

@@ -1135,22 +1135,16 @@
 nt) %7B%0A%09%09
-final 
 Number c
@@ -1150,16 +1150,28 @@
 count = 
+null;%0A%09%09if (
 amount !
@@ -1168,34 +1168,46 @@
  (amount != null
- ?
+) %7B%0A%09%09%09count =
  amount.getSingl
@@ -1218,12 +1218,13 @@
 ent)
- : 1
+;%0A%09%09%7D
 ;%0A%09%09
@@ -1245,19 +1245,28 @@
 ull)
+ %7B
 %0A%09%09%09
-return;
+count = 1;%0A%09%09%7D
 %0A%09%09M

Fix potential NPE in EffSpawn count parsing