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