package com.zivilon.cinder_loe.command;

import com.zivilon.cinder_loe.carriage.CarriageDestination;
import com.zivilon.cinder_loe.carriage.CarriageDestinationsData;
import com.zivilon.cinder_loe.carriage.CarriageRoadRegistry;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import org.apache.commons.lang3.StringUtils;

public class CommandSetDestination extends CommandBase {
    @Override
    public String getCommandName() {
        return "set_destination";
    }

    @Override
    public String getCommandUsage(ICommandSender sender) {
        return "/set_destination \"Destination Name\" roadId";
    }

    @Override
    public void processCommand(ICommandSender sender, String[] args) throws CommandException {
        if (args.length < 2) {
            throw new WrongUsageException(getCommandUsage(sender));
        }

        // last arg is the road ID
        String roadId = args[args.length - 1].toLowerCase();
        if (CarriageRoadRegistry.getRoad(roadId) == null) {
            throw new CommandException("Unknown road ID: " + roadId);
        }

        // everything before is the destination name
        String name = StringUtils.join(args, " ", 0, args.length - 1);

        if (!(sender instanceof EntityPlayerMP)) {
            throw new CommandException("Must be run by a player.");
        }

        EntityPlayerMP player = (EntityPlayerMP) sender;
        World world = player.worldObj;

        int x = (int) Math.floor(player.posX);
        int y = (int) Math.floor(player.posY);
        int z = (int) Math.floor(player.posZ);
        int dim = player.dimension;

        CarriageDestinationsData data = CarriageDestinationsData.get(world);
        if (data == null) {
            throw new CommandException("Failed to access destination storage.");
        }

        data.addDestination(new CarriageDestination(name, x, y, z, dim, roadId));
        sender.addChatMessage(new ChatComponentText(
                EnumChatFormatting.YELLOW + "Destination '" + name + "' on road '" + roadId + "' saved."
        ));
    }
}
