package me.despawningbone.discordbot.command.misc;

import java.util.Arrays;

import me.despawningbone.discordbot.command.Command;
import me.despawningbone.discordbot.command.CommandResult;
import me.despawningbone.discordbot.command.CommandResult.CommandResultType;
import me.despawningbone.discordbot.utils.MiscUtils;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.User;

public class BaseConvert extends Command {
	public BaseConvert() {
		this.alias = Arrays.asList("bc");
		this.desc = "convert integers of a base to another base!";
		this.usage = "[frombase] <base> <int>";
		this.examples = Arrays.asList("2 100", "16 8 FF");
	}

	@Override
	public CommandResult execute(TextChannel channel, User author, Message msg, String[] args) {  //base 1 is weird, fix?
		String x = "0";
		long base = 10;
		long frombase = 10;
		
		try {
			if(args.length < 2)
				return new CommandResult(CommandResultType.INVALIDARGS, "Please enter "  + (args.length < 1 ? "something :joy:" : "a value to convert."));
			
			if (args.length < 3) {  //only specify to base
				try { base = Long.parseLong(args[0]); } catch (NumberFormatException e) { base = MiscUtils.nameToBase(args[0]); }
				x = args[1];
			} else {                //specify both bases
				try { frombase = Long.parseLong(args[0]); } catch (NumberFormatException e) { frombase = MiscUtils.nameToBase(args[0]); }
				try { base = Long.parseLong(args[1]); } catch (NumberFormatException e) { base = MiscUtils.nameToBase(args[1]); }
				x = args[2];	
			}
			
			if (base > 30 || frombase > 30)
				return new CommandResult(CommandResultType.INVALIDARGS, "Please enter a base smaller than 30.");
				
			try {
				channel.sendMessage("Base" + MiscUtils.longToSubscript(frombase) + ": `" + x.toUpperCase() + "`\n" + "Base"
						+ MiscUtils.longToSubscript(base) + ": `"
						+ Long.toString(Long.parseLong(x, (int) frombase), (int) base).toUpperCase() + "`").queue();
				return new CommandResult(CommandResultType.SUCCESS);
			} catch (NumberFormatException e) {
				return new CommandResult(CommandResultType.INVALIDARGS, "Please enter a valid value within the base range specified.");
			}
		} catch (IllegalArgumentException e) {
			return new CommandResult(CommandResultType.INVALIDARGS, e.getMessage());
		}
	}

}
