package me.blackphreak.CommandHandling;

import me.blackphreak.Debug.Debug;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

import static me.blackphreak.Lib.*;

public class CommandHandler {
	// use hashmap to remove duplicated handlers
	private static HashMap</*cmd*/String, AbstractCommandHandler> commandMap = new HashMap<>();
	
	static void registerHandler(String cmd, AbstractCommandHandler handler) {
		commandMap.put(cmd, handler);
	}
	
	/*public static void deregisterHandler(String cmd) {
		commandMap.remove(cmd);
	}*/
	
	public static void printOptions() {
		String inp;
		int chosen;
		
		do {
			System.out.println("Actions:");
			
			AtomicInteger i = new AtomicInteger();
			commandMap.forEach((cmd, handler) -> System.out.println(String.format(
					"  %2s. %-15s %s",
					i.incrementAndGet() + "",  // ++i
					cmd,
					handler.description
			)));
			
			inp = promptQuestion(String.format(
					"Please select an action (1 - %d): ",
					commandMap.size()
			));
			
			// input validation & parsing
			chosen = tryParseUInt(inp);
			
			if (chosen == -1)
				continue;  // loop
			
			if (chosen <= 0
					|| chosen > commandMap.size())
			{
				System.out.println("Invalid action. (Must in between 1 to "+(commandMap.size())+", inclusive)");
				chosen = -1;  // keep the loop
			}
			else
			{
				// index offset ("i" is count from "1",
				//   but array is counting from "0")
				chosen--;
			}
			
			// loop until a valid option is picked. (chosen != -1)
		} while (chosen == -1);
		
		// pass to the command handler for rest of the actions.
		((AbstractCommandHandler)(commandMap.values().toArray()[chosen])).handle();
	}
}
