import java.util.ArrayList;

/**
 * A list of network users stored in ASCII order by login name.
 *
 * @author Drue Coles
 */
public class SortedListOfNetworkUsers {

    private final ArrayList<NetworkUser> users;

    /**
     * Creates an empty list of network users.
     */
    public SortedListOfNetworkUsers() {
        users = new ArrayList<>();
    }

    /**
     * Returns the network user at a given position in the list.
     */
    public NetworkUser get(int i) {
        return users.get(i);
    }

    /**
     * Returns the size of the list.
     */
    public int size() {
        return users.size();
    }

    /**
     * Adds a network user to this list at its correct position with respect to login name.
     */
    public void add(NetworkUser user) {
        int i = 0; // position at which to insert
        String nameToAdd = user.getLogin();

        while (i < size()) {
            String nameInList = get(i).getLogin();
            if (nameToAdd.compareTo(nameInList) <= 0) {
                break;
            }
            i++;
        }
        users.add(i, user);
    }

    /**
     * Test program that adds four network users to a list and then traverses the list to
     * verify that the objects are stored in ascending order by login name. 
     */
    public static void main(String[] args) {
        SortedListOfNetworkUsers users = new SortedListOfNetworkUsers();
        NetworkUser n1 = new NetworkUser("washington", "usa123");
        NetworkUser n2 = new NetworkUser("adams", "july4hello");
        NetworkUser n3 = new NetworkUser("jefferson", "virginia1743");
        NetworkUser n4 = new NetworkUser("madison", "password");
        users.add(n1);
        users.add(n2);
        users.add(n3);
        users.add(n4);
        
        // output contents of list to verify order
        for (int i = 0; i < users.size(); i++) {
            System.out.println(users.get(i));
        }
    }
}