package me.km.snuviscript.commands;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import me.hammerle.snuviscript.code.Script;
import me.hammerle.snuviscript.code.ScriptManager;
import me.km.snuviscript.Scripts;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.MinecraftServer;

public class ScriptCommands {
    private static void nothing(Script sc) {
    }

    public static void registerFunctions(ScriptManager sm, Scripts scripts, MinecraftServer server) {
        sm.registerConsumer("script.callevent", (sc, in) -> {
            String name = in[0].getString(sc);
            if(in.length >= 2) {
                sm.callEvent(name, (Script) in[1].get(sc), ScriptCommands::nothing, ScriptCommands::nothing);
            } else {
                sm.callEvent(name, ScriptCommands::nothing, ScriptCommands::nothing);
            }
        });
        sm.registerFunction("script.playerstolist", (sc, in) -> new ArrayList<>(scripts.getPlayerList(sc.getId())));
        sm.registerFunction("script.getplayeramount", (sc, in) -> (double) scripts.getPlayerList(sc.getId()).size());
        sm.registerFunction("script.start", (sc, in) -> {
            Object o = in[0].get(sc);
            if(o instanceof PlayerEntity) {
                String[] names = new String[in.length - 1];
                for(int i = 1; i < in.length; i++) {
                    names[i - 1] = in[i].getString(sc);
                }
                return scripts.startPlayerScript((PlayerEntity) in[0].get(sc), names);
            }
            String[] names = new String[in.length];
            names[0] = o.toString();
            for(int i = 1; i < in.length; i++) {
                names[i] = in[i].getString(sc);
            }
            return scripts.startScript(null, names);
        });
        sm.registerFunction("script.startnamed", (sc, in) -> {
            String[] names = new String[in.length -1];
            for(int i = 0; i < names.length; i++) {
                names[i] = in[i + 1].getString(sc);
            }
            return scripts.startScript(in[0].getString(sc), names);
        });
        sm.registerFunction("script.join", (sc, in) -> scripts.registerPlayer((Script) in[0].get(sc), (PlayerEntity) in[1].get(sc)));
        sm.registerFunction("script.kick", (sc, in) -> scripts.unregisterPlayer(sc, (PlayerEntity) in[0].get(sc)));
        sm.registerFunction("script.getleader", (sc, in) -> {
            List<UUID> players = scripts.getPlayerList(sc.getId());
            if(players.isEmpty()) {
                return null;
            }
            return server.getPlayerList().getPlayerByUUID(players.get(0));
        });
    }
}
