package controller.console.administrateur;

import java.util.Scanner;
import java.util.ArrayList;

import model.Module;
import model.list.HandlerModules;
import view.console.administrateur.Module_Creation;

public class Module_CreationControle {
	private Scanner sc;
	private ArrayList<Module> choice_list;
	
	private String libelle;
	private String syllabus;
	private ArrayList<Module> pere;
	
	private class InputDone extends Exception {
		private static final long serialVersionUID = 1L;
	}
	
	public Module_CreationControle(ArrayList<Module> liste_modules) {
		this.choice_list = new ArrayList<Module>();
		this.pere = new ArrayList<Module>();
		this.choice_list.addAll(liste_modules);
		sc = new Scanner(System.in);
		boolean done = false;
		
		Module_Creation.trigger();
		Module_Creation.askLibelle();
		this.askLibelle();
		Module_Creation.askSyllabus();
		this.askSyllabus();
		while (!done) {
			try {
				Module_Creation.askModules(this.choice_list);
				Module_Creation.currentModules(this.pere);
				this.askPere();
			} catch (NumberFormatException e) {
				Module_Creation.fail((-1)*pere.size(),choice_list.size());
			} catch (InputDone e) {
				done = true;
			}
		}
		
	}
	
	private void askLibelle() {
		String input;
		input = sc.nextLine();
		this.libelle = input;
	}
	
	private void askSyllabus() {
		String input;
		input = sc.nextLine();
		this.syllabus = input;
	}
	
	private void askPere() throws NumberFormatException, InputDone {
		int input;
		String str_input;

		str_input = this.sc.nextLine();
		input = Integer.parseInt(str_input);
		if ((input < (-1)*pere.size()) || (input > choice_list.size())) {
			throw new NumberFormatException();
		} else if (input > 0) {
			input--;
			pere.add(choice_list.get(input));
			Module_Creation.addModulePere(choice_list.get(input));
			choice_list.remove(input);
		} else if (input < 0) {
			input++;
			input = input*(-1);
			choice_list.add(pere.get(input));
			Module_Creation.removeModulePere(pere.get(input));
			pere.remove(input);
		} else {
			throw new InputDone();
		}
	}
	
	public void addToDatabase(HandlerModules hMod) {
		Module m = new Module(this.libelle, this.syllabus, this.pere);
		hMod.addListe(m);
		Module_Creation.addModule(m);
	}
}
