package authentication;

import java.util.ArrayList;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;





public class Authentication implements AuthenticationManager{
	
	
	ArrayList <User> listeUser = new ArrayList <User>();
	
	ObjectInputStream ois;
    ObjectOutputStream oos;
	
	public void addUser(String login, String password) throws UserExistsException{
		
			for(int i=0; i<listeUser.size(); i++){
				if(listeUser.get(i).getLogin()==login){
					throw new UserExistsException(login);
			}
		}
		listeUser.add(new User(login, password));
	}
	
	public void removeUser(String login) throws UserUnknownException{
		
		for(int i = 0; i < listeUser.size(); i++)
        {
                if(listeUser.get(i).getLogin()==login){
               	 listeUser.remove(i);
                }
                else{
                	throw new UserUnknownException(login);
                }
        }    
		
	}
	
	public void authentify (String login, String password) throws UserExistsException, WrongPasswordException{
		for(int i=0; i<listeUser.size(); i++){
			if(listeUser.get(i).getLogin()== login && listeUser.get(i).getPassword()!=password){
				throw new WrongPasswordException(login);
			}
		}
		
	}
	public AuthenticationManager load(String path){
		
        
    	try {
			
    		ois = new ObjectInputStream(
    				new BufferedInputStream(
    						new FileInputStream(
    								new File(path))));
    		ois.close();
    		
		} catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }  
        return 
	}
	
	public void save(String path){
		try {
        	oos = new ObjectOutputStream(
        				new BufferedOutputStream(
        						new FileOutputStream(
        								new File(path))));
        	for(int i=0; i<listeUser.size() ; i++){
        	oos.writeObject(listeUser.get(i)); 
        	}
        	oos.close();	
	    }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }     	
    }

	
	
	/******************************* constructeur*************************/
	
	public Authentication(ArrayList<User> liste)throws AuthenticationException,UserExistsException,WrongPasswordException,IOException {
		super();
		listeUser = liste;
	}
	
	
}
