package me.blackphreak.CommandHandling;

import me.blackphreak.Database;
import me.blackphreak.Debug.Debug;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static me.blackphreak.Lib.promptQuestion;

public abstract class AbstractEditCommandHandler extends AbstractCommandHandler {
	protected String lastCmd;
	protected List<String> selectedStudentID;
	
	protected AbstractEditCommandHandler(String desc) {
		super(desc);
	}
	
	/**
	 * Ask user to provide student ID before editing the targeted student(s).
	 * @return true when selected at least one student, otherwise, false.
	 */
	protected boolean selectStudentByID(boolean allowMultiple) {
		// reset
		selectedStudentID = new ArrayList<>();
		lastCmd = null;
		
		do {
			if (allowMultiple)
				System.out.println("\n** type \"next\" to stop providing StudentID **");
			System.out.println("** type \"exit\" to back to main menu **");
			
			if (allowMultiple)
				System.out.println("\nSelected StudentID(#"+selectedStudentID.size()+"): " + Arrays.toString(selectedStudentID.toArray()));
			
			var inp = promptQuestion("Please provide StudentID: ", false);
			
			if (allowMultiple && inp.equalsIgnoreCase("next"))
			{
				if (selectedStudentID.size() <= 0)
					System.out.println("Please provide at least one student ID before edit.");
				else
					return true;
			}
			else if (inp.equalsIgnoreCase("exit"))
			{
				lastCmd = "exit";  // back to main menu
				return false;
			}
			else
			{
				// query database to confirm that student is exist.
				try {
					if (Database.getInstance()
							.query("SELECT COUNT(*) FROM Student WHERE StudentID = \""+inp+"\";")
							.getInt(1) != 1)
					{
						System.out.println("Invalid StudentID, please try again. [Failed to select (!=1)]");
						continue;
					}
				} catch (SQLException e) {
					Debug.err("Failed to find student. (Database Error)");
					e.printStackTrace();
					lastCmd = "end";  // end the program
					return false;
				}
				
				selectedStudentID.add(inp);
			}
		} while (allowMultiple);
		
		return true;
	}
}
