package authentification;

import java.io.*;
import java.util.*;

public class Authentification implements GestAuthentification,Serializable {

	private static final long serialVersionUID = 1L;
	private SortedSet<User> users;
	
	public Authentification () {
		users = new TreeSet<User>();
	}

	public void addUser(String login, String pass) throws UserExists {
		User newby = new User(login,pass);
		if (users.contains(newby)) {
			throw new UserExists(login);
		} else {
			users.add(newby);
		}
	}

	public void removeUser(String login) throws UserUnknown {		
		User newby = new User(login,"");
		if (! users.contains(newby)) {
			throw new UserUnknown(login);
		} else {
			users.remove(newby);
		}
	}

	public void authentify(String login, String pass) throws UserUnknown,
			WrongPassword {
		User newby = new User(login,"");
		if (! users.contains(newby)) {
			throw new UserUnknown(login);
		} else {
			User connu = users.headSet(new User(login+"\0","")).last();
			if (! connu.getPass().equals(pass)) 
				throw new WrongPassword(login);
		}
	}

	@SuppressWarnings("unchecked")
	public void charger(String path) throws IOException {
		users.clear();
		ObjectInputStream in = new ObjectInputStream (new FileInputStream(path));
		try {
			users =  (TreeSet<User>) in.readObject();
		} catch (ClassNotFoundException e) {
			throw new IOException("probleme de version de classes"+e);
		}
	}

	public void sauver(String path) throws IOException {
		ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream(path));
		out.writeObject(users);
	}

	
}
