import java.io.*;
import java.util.*;


public class Pool implements Iterable<EistiStudent>{
	
	private String name;
	private SortedSet<EistiStudent> etudiants;
	
	public Pool(String name) {
		this.name = name;
		this.etudiants = new TreeSet<EistiStudent>();
	}

	public Pool(String name,String nomFichier) throws ClassNotFoundException {
		this.name = name;
		this.etudiants = this.lectureFichier(nomFichier);
	}
	
	public boolean addStudent(EistiStudent e)
	{
		return this.etudiants.add(e);
	}
	
	public boolean removeStudent(EistiStudent e)
	{
		return this.etudiants.remove(e);
	}
	
	public String toString()
	{
		return "Groupe : "+this.getName()+" ; Taille : "+this.getTaille()+"\n";
	}
	
	public String getName() {
		return name;
	}

	public int getTaille()
	{
		return this.etudiants.size();
	}
	
	public TreeSet<EistiStudent> lectureFichier(String nomFichier) throws ClassNotFoundException 
	{
		TreeSet<EistiStudent> ts = new TreeSet<EistiStudent>();
		
		try {
			// On crée le fichier correspondant au nom passer en paramètre
			File f = new File(nomFichier);
			// On crée un flux vers le fichier
			FileInputStream fis = new FileInputStream(f);
			// On crée un flux de lecture d'objet
			ObjectInputStream ois = new ObjectInputStream(fis);
			// On lit des objets dans le fichier tant qu'il en reste
			while (fis.available() > 0) {
			
				// On lit un objet
				EistiStudent tmp =  (EistiStudent) ois.readObject();
				
				// On l'ajoute
				ts.add(tmp);
			}
			
			// On ferme le ObjectInputStream
			
			ois.close();
			
			// On ferme le FileInputStream
			
			fis.close();
			
		} catch (FileNotFoundException e) {
		
			e.printStackTrace();
			
		} catch (IOException e) {
		
			e.printStackTrace();
			
		}
		
		return ts;
	}
	
	public Iterator<EistiStudent> iterator(OrderType ordre) {
		List<EistiStudent> l = trierEtudiant(ordre);
		return l.iterator();
	}
	
	
	@Override
	public Iterator<EistiStudent> iterator() {
		return this.etudiants.iterator();
	}
	
	
	@SuppressWarnings("unchecked")
	public List<EistiStudent> trierEtudiant(OrderType order)
	{
		ArrayList<EistiStudent> l = new ArrayList<EistiStudent>(this.etudiants);
		switch(order){
			case ASCENDING:
				Collections.sort(l);
				break;
			case DESCENDING:
				Collections.sort(l,Collections.reverseOrder());
				break;
			default :
				break;
		}
		return l;
	}
	
}
