package controller.console.eleve;

import java.util.ArrayList;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Scanner;

import view.console.eleve.Session_Rendu;

import model.Eleve;
import model.Rendu;
import model.Reponse;
import model.Session;
import model.list.HandlerRendus;

public class Session_RenduControle {
	private Scanner sc;
	
	private Date dateRendu;
	private Eleve eleve;
	private Session session;
	private ArrayList<Reponse> reponsesChoisies;
	private ArrayList<Reponse> r_tmp;
	
	public class NoEntry extends Exception {
		private static final long serialVersionUID = 1L;
	}
	
	public Session_RenduControle(Eleve e_connected, Session s, ArrayList<Rendu> lRendu) throws NoEntry {
		this.sc = new Scanner(System.in);
		this.dateRendu = new Date();
		this.eleve = e_connected;
		this.session = s;
		this.reponsesChoisies = new ArrayList<Reponse>();
		this.r_tmp = new ArrayList<Reponse>();
		
		int tentative = HandlerRendus.getTimesAnswered(this.session, this.eleve, lRendu);
		
		Session_Rendu.trigger();
		if (this.dateRendu.after(this.session.getDateFin())) {
			Session_Rendu.tooLate();
			throw new NoEntry();
		} else if (tentative >= this.session.getRepetition()) {
			Session_Rendu.tooMuch();
			throw new NoEntry();
		} else {
			Session_Rendu.showSession(tentative, this.session);
			this.askQuestions();
		}
	}
	
	public void askQuestions() {
		int i;
		boolean done;
		int input;		
		
		for (i = 0 ; i < this.session.getQcm().getQuestions().size() ; i++) {
			done = false;
			this.r_tmp.clear();
			while (!done) {
				Session_Rendu.showQuestion(i+1, this.session.getQcm().getQuestions().get(i));
				Session_Rendu.showSelected(r_tmp);
				try {
					input = sc.nextInt();
					if (input < 0 || input > this.session.getQcm().getQuestions().get(i).getReponses().size()) {
						throw new InputMismatchException();
					} else if (input == 0) {
						done = true;
					} else {
						if (r_tmp.contains(this.session.getQcm().getQuestions().get(i).getReponses().get(input-1))) {
							r_tmp.remove(this.session.getQcm().getQuestions().get(i).getReponses().get(input-1));
						} else {
							r_tmp.add(this.session.getQcm().getQuestions().get(i).getReponses().get(input-1));
						}
					}
					sc.nextLine();
				} catch (InputMismatchException e) {
					sc.nextLine();
					Session_Rendu.fail(0, this.session.getQcm().getQuestions().get(i).getReponses().size());
				}
			}
			this.reponsesChoisies.addAll(r_tmp);
		}
	}
	
	public void terminate(HandlerRendus hRendus) {
		hRendus.getListe().add(new Rendu(this.dateRendu, this.eleve, this.session, this.reponsesChoisies));
		hRendus.updateDatabase();
		Session_Rendu.itIsDone();
	}
}
