package me.blackphreak.CommandHandling;

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

import static me.blackphreak.Lib.promptQuestion;
import static me.blackphreak.Lib.tryParseUInt;

public class CommandHandler {
	// use hashmap to remove duplicated handlers if any
	private static HashMap</*cmd*/String, AbstractCommandHandler> commandMap = new HashMap<>();
	
	static void registerHandler(String cmd, AbstractCommandHandler handler) {
		commandMap.put(cmd, handler);
	}
	
	/**
	 * print the option menu, nothing special
	 */
	public static void printOptions() {
		String inp;
		int chosen;
		
		do {
			System.out.println("\nActions:");
			
			AtomicInteger i = new AtomicInteger();
			commandMap.forEach((cmd, handler) -> System.out.println(String.format(
					"  %2s. %-15s %s",
					i.incrementAndGet() + "",  // ++i
					cmd,
					handler.description
			)));
			
			// exit option
			System.out.println(String.format(
					"  %2s. %-15s %s",
					"99",
					"Exit",
					"Close this application"
			));
			
			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())
			{
				if (chosen == 99)
				{
					// exit
					System.out.println("Exiting... Bye~");
					break;
				}
				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--;
			}
			
			if (chosen == -1)
				continue;
			
			// pass to the command handler for rest of the actions.
			if (!((AbstractCommandHandler)(commandMap.values().toArray()[chosen])).handle())
				break;  // exit
			
		} while (true);
	}
}
