package apz.pirichat.server;
import java.util.Vector;
import apz.pirichat.shared.PiriException;
import apz.pirichat.shared.PiriIDInUseException;
import apz.pirichat.shared.PiriNotFoundException;

public class Users
{
    private Vector<User> mUsers;

    public Users()
    {
        mUsers = new Vector<User>();
    }

    public boolean doesUserExist(String pUserName)
    {
        // Check to see whether user exists or not
        return (lookupUserIndex(pUserName) != (-1));
    }

    public User[] getUsers()
    {
        // Return array containing all users
        User[] tempArray = new User[mUsers.size()];
        for(int i=0; i<mUsers.size(); i++)
            tempArray[i] = (User)mUsers.elementAt(i);
        return tempArray;
    }

    public User getUser(String pUserName) throws PiriNotFoundException
    {
        // Lookup user index. If user is not found, return null
        int index = lookupUserIndex(pUserName);
        if (index == (-1))
            throw new PiriNotFoundException(pUserName);
        return (User)mUsers.elementAt(index);
    }

    public User createUser(String pUserName, String pPassword) throws PiriException
    {
        // Check to see whether anyone with that username already exists
        // If so, throw error
        if (doesUserExist(pUserName))
            throw new PiriIDInUseException(pUserName);
        // Create an instance of our new user
        User currentUser = new User(pUserName, pUserName, pPassword, User.Group.GROUP_DEFAULT);
        // Add it to our list, and return it to user
        mUsers.add(currentUser);
        return currentUser;
    }

    private int lookupUserIndex(String pUserName)
    {
        for(int i=0; i<mUsers.size(); i++)
            if (((User)mUsers.elementAt(i)).getUserName().equals(pUserName)) return i;
        return (-1);
    }
}
