package controller.console.administrateur;

import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

import view.console.administrateur.Module_Suppression;

import model.Module;
import model.list.HandlerModules;

public class Module_SuppressionControle {
	private Scanner sc;
	private ArrayList<Module> liste_modules;
	private Module m;
	
	private class InputDone extends Exception {
		private static final long serialVersionUID = 1L;
	}
	
	private class ModuleNotFound extends Exception {
		private static final long serialVersionUID = 1L;
	}
	
	public Module_SuppressionControle(ArrayList<Module> liste_modules) {
		this.liste_modules = liste_modules;
		boolean done = false;
		sc = new Scanner(System.in);
		
		Module_Suppression.trigger();
		while (!done) {
			Module_Suppression.showModules(this.liste_modules);
			try {
				this.getModule();
				Module_Suppression.areYouSure(this.m);
				if (this.getAreYouSure()) {
					this.removeModule();
					Module_Suppression.removeModule(this.m);
				}
			} catch (InputMismatchException e) {
				Module_Suppression.fail(0,this.liste_modules.size());
			} catch (ModuleNotFound e) {
				Module_Suppression.failLogin();
			} catch (InputDone e) {
				done = true;
			}
		}
		
	}
	
	private void getModule() throws InputMismatchException, ModuleNotFound, InputDone {
		String str_input;
		int input;

		str_input = sc.nextLine();
		try {
			input = Integer.parseInt(str_input);
			if ((input < 0) || (input > this.liste_modules.size())) {
				throw new InputMismatchException();
			} else if (input == 0) {
				throw new InputDone();
			} else {
				this.m = this.liste_modules.get(input-1);
			}
		} catch (NumberFormatException e) {
			this.m = HandlerModules.getModule(str_input, this.liste_modules);
			if (this.m == null) {
				throw new ModuleNotFound();
			}
		}
	}
	
	private boolean getAreYouSure() {
		String input = sc.nextLine();
		return (input.startsWith("o") || input.startsWith("O"));
	}
	
	private void removeModule() {
		this.liste_modules.remove(this.m);
	}
	
	public void updateDatabase() {
		Module_Suppression.updateDatabase();
	}
}
