package org.ultramine.mods.hawkeye.commands;

import org.ultramine.mods.hawkeye.DataType;
import org.ultramine.mods.hawkeye.HawkEye;
import org.ultramine.mods.hawkeye.SearchParser;
import org.ultramine.mods.hawkeye.callbacks.SearchCallback;
import org.ultramine.mods.hawkeye.database.SearchQuery;
import org.ultramine.mods.hawkeye.database.SearchQuery.SearchDir;
import org.ultramine.mods.hawkeye.util.HawkPermission;
import org.ultramine.mods.hawkeye.util.HawkUtil;

/**
 * Searches around the player for 'here' {@link DataType}s
 * 
 * @author oliverw92
 */
public class HereCommand extends BaseCommand
{
	public HereCommand()
	{
		name = "here";
		argLength = 0;
		usage = "[radius] [player] <- search around you";
	}

	@Override
	public boolean execute()
	{
		//Create new parser
		SearchParser parser = null;
		try
		{
			//Check for valid integer
			if(args.size() != 0 && !HawkUtil.isInteger(args.get(0)))
				throw new IllegalArgumentException("Invalid integer supplied for radius!");
			int integer;
			if(args.size() > 0)
				integer = Integer.parseInt(args.get(0));
			else
				integer = HawkEye.instance.config.general.defaultHereRadius;
			if((integer > HawkEye.instance.config.general.maxRadius && HawkEye.instance.config.general.maxRadius > 0) || integer < 0)
				throw new IllegalArgumentException("Invalid radius supplied supplied!");

			//New search parser
			parser = new SearchParser(sender, integer);

			//Add in DataTypes
			for(DataType type : DataType.values())
				if(type.canHere())
					parser.actions.add(type);

			//Check if players were supplied
			if(args.size() > 1)
				for(String p : args.get(1).split(","))
					parser.players.add(p);

			//Add in 'here' actions
			for(DataType type : DataType.values())
				if(type.canHere())
					parser.actions.add(type);
		}
		catch(IllegalArgumentException e)
		{
			HawkUtil.sendMessage(sender, "&c" + e.getMessage());
			return true;
		}

		//Run the search query
		new SearchQuery(new SearchCallback(session), parser, SearchDir.DESC);
		return true;
	}

	@Override
	public void moreHelp()
	{
		HawkUtil.sendMessage(sender, "&cShows all changes in a radius around you");
		HawkUtil.sendMessage(sender, "&cRadius should be an integer");
	}

	@Override
	public boolean permission()
	{
		return HawkPermission.search(sender);
	}
}
