package me.km.scrolls;

import java.util.Arrays;
import java.util.stream.Collectors;
import me.km.api.GlobalText;
import me.km.api.Module;
import me.km.api.ModuleTabCommand;
import me.km.effects.Effect;
import me.km.items.ModItems;
import me.km.permissions.Permissions;
import net.minecraft.block.Block;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;

public class CommandScroll extends ModuleTabCommand
{
    public CommandScroll(Module m) 
    {
        super("magicscroll", m, Arrays.stream(Effect.values())
                .filter(n -> n.isActive())
                .map(n -> n.toString())
                .collect(Collectors.toList()), 0);
        super.setDescription("Erstellt Schriftrollen, Unterstriche bei <dname> werden zu Leerzeichen");
        super.setUsage("/magicscroll <name> <dname> [level] [amount]");
        super.setPermission(Permissions.SCROLL);
        super.addAlias("msc");
    }

    @Override
    public boolean execute(ICommandSender cs, String[] arg) 
    {
        if(arg.length < 2)
        {
            return false;
        }
        if(!(cs instanceof EntityPlayer))
        {
            this.getModule().send(cs, GlobalText.onlyPlayer());
            return true;
        }
        EntityPlayer p = (EntityPlayer) cs;
        Effect eff = Effect.valueOf(arg[0]);
        if(eff == null || !eff.isActive())
        { 
            this.getModule().send(cs, "Dieser aktive Effekt existiert nicht.");
            return true;
        }
        int level;
        try
        {               
            level = Integer.parseInt(arg[2]);
            if(level <= 0)
            {
                this.getModule().send(cs, GlobalText.noPositiveNaturalNumber());
                return true;
            }
        }
        catch(NumberFormatException | ArrayIndexOutOfBoundsException ex)
        {
            level = 1;
        }
        int amount;
        try
        {               
            amount = Integer.parseInt(arg[3]);
            if(amount <= 0)
            {
                this.getModule().send(cs, GlobalText.noPositiveNaturalNumber());
                return true;
            }
        }
        catch(NumberFormatException | ArrayIndexOutOfBoundsException ex)
        {
            amount = 1;
        }     
        ItemStack stack = new ItemStack(ModItems.scroll, amount);
        ModItems.scroll.setEffect(stack, eff.ordinal(), level, arg[1].replace('_', ' '));
        Block.spawnAsEntity(p.world, p.getPosition(), stack);
        return true;
    }
}