package me.km.snuviscript.commands;

import me.hammerle.snuviscript.code.ScriptManager;
import me.hammerle.snuviscript.code.SnuviUtils;
import me.km.utils.ItemStackUtils;
import me.km.utils.Location;
import me.km.utils.Mapper;
import me.km.utils.Utils;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.server.ServerWorld;

public class ReadCommands {
    public static void registerFunctions(ScriptManager sm, MinecraftServer server) {
        sm.registerFunction("read.player", (sc, in) -> Utils.getPlayerByName(server, in[0].getString(sc)));
        sm.registerFunction("read.location", (sc, in) -> new Location(server, in[0].getString(sc)));
        sm.registerFunction("read.item", (sc, in) -> {
            String s = in[0].getString(sc);
            if(s.startsWith("{")) {
                String left = SnuviUtils.connect(sc, in, 1);
                return ItemStackUtils.getStackFromNbtString(s + left);
            }
            Item item = Mapper.getItem(s);
            int amount = in.length >= 2 ? in[1].getInt(sc) : 1;
            ItemStack stack = new ItemStack(item, amount);
            if(in.length >= 3) {
                stack.setDisplayName(new StringTextComponent(in[2].getString(sc)));
            }
            if(in.length >= 4) {
                for(int i = 3; i < in.length; i++) {
                    ItemStackUtils.addLore(stack, in[i].getString(sc));
                }
            }
            return stack;
        });
        sm.registerFunction("read.spawnmob", (sc, in) -> {
            Location l = (Location) in[0].get(sc);
            ServerWorld sw = (ServerWorld) l.getWorld();
            CompoundNBT compoundnbt = JsonToNBT.getTagFromJson(SnuviUtils.connect(sc, in, 1));
            Entity entity = EntityType.func_220335_a(compoundnbt, sw, (ent) -> {
                ent.setLocationAndAngles(l.getX(), l.getY(), l.getZ(), ent.rotationYaw, ent.rotationPitch);
                return sw.summonEntity(ent) ? ent : null;
            });
            return entity;
        });
    }
}
