package totale.p240116;

import java.util.Set;
import java.util.TreeSet;
import java.util.Comparator;
import java.util.Iterator;

public class Universita {

	Set<Docente> docenti = new TreeSet<Docente>(new Comparator<Docente>() {
		@Override
		public int compare(Docente d1, Docente d2) {
			int cmp;
			// By age
			cmp = Integer.compare(d1.eta(),d2.eta());
			if (cmp != 0) return cmp;
			// By surname
			cmp = d1.cognome().compareTo(d2.cognome());
			if (cmp != 0) return cmp;
			// By name
			cmp = d1.nome().compareTo(d2.nome());
			if (cmp != 0) return cmp;
			// Last chance ID
			return d1.ORCID().compareTo(d2.ORCID());
		}
	});
	
	// Method 1
	public boolean aggiungi(
			String ORCID,
			String nome,
			String cognome,
			int eta) {
		// Null check
		if (ORCID == null || nome == null || cognome == null) throw new NullPointerException();
		// New Object
		Docente newDocente = new Docente(ORCID, nome, cognome, eta);
		// ID check
		for (Docente d : docenti) {
			if (d.ORCID().equals(ORCID)) return false;
		}
		// Add to Set
		return docenti.add(newDocente);
	}
	
	// Method 2
	public boolean presente(String ORCID) {
		// Null check
		if (ORCID == null) throw new NullPointerException();
		// ID check
		for (Docente d : docenti) {
			if (d.ORCID().equals(ORCID)) return true;
		}
		// Final result
		return false;
	}
	
	// Method 3
	public boolean rimuovi(String ORCID) {
		// Null check
		if (ORCID == null) throw new NullPointerException();
		// ID remove
		Iterator<Docente> it = docenti.iterator();
		while (it.hasNext()) {
			if (it.next().ORCID().equals(ORCID)) {
				it.remove();
				return true;
			}
		}
		// If not exists
		return false;
	}
	
	// Method 4
	public int etaMinima() {
		// Empty check
		if (docenti.isEmpty()) return 0;
		// First Docente is minimum age
		return docenti.iterator().next().eta();
	}
	
	// Method 5
	public Set<Docente> rispettoORCID() {
		Set<Docente> docenteById = new TreeSet<Docente>();
		docenteById.addAll(docenti);
		return docenteById;
	}
	
}
