#include "BST"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

/* Program to validates computer user-ids and passwords.  A list of
 * valid ids and passwords is read from UsersFile and is stored in 
 * a BST.  When user-ids and passwords are entered during execution, 
 * this BST is searched to determine whether they are legal.
 *
 *  Input (file):     UserInfo records for valid users 
 *  Input (keyboard): Ids and passwords of users logging in
 *  Output (screen):  Messages indicating whether user-ids and 
 *                      passwords are valid
 ********************************************************************/

//--- Struct containing user information ----------------//
//    with >>, ==, and < operators
struct UserInfo
{
  string id,
         password;
};

//--- equals operator
inline bool operator==(const UserInfo & user1,
                       const UserInfo & user2)
{ return user1.id == user2.id &&
         user1.password == user2.password; }

//--- less-than operator
inline bool operator<(const UserInfo & user1,
                      const UserInfo & user2)
{ return user1.id < user2.id; }

//--- greater-than operator
inline bool operator>(const UserInfo & user1,
		                            const UserInfo & user2)
{ return user1.id > user2.id; }

//--- input operator
istream & operator>>(istream & in, UserInfo & user)
{
  in >> user.id >> user.password;
  return in;
}

//--------------------------------------------------------//

int main()
{
  // Open file of legal user-ids and password
  ifstream userFile("UsersFile");
  if (!userFile.is_open())
  {
    cerr << "Cannot open UsersFile\n";
    exit(-1);
  }

  // Build the BST of user records
  BST<UserInfo> userTree;   // BST of user records
  UserInfo user;            // a user record
  for (;;)
  {
    userFile >> user;
    if (userFile.eof()) break;

    userTree.Insert(user);
  }

  // Validate logins
  cout << "Enter Q Q to stop processing.\n";

  for (;;)
  {
    cout << "\nUser id & password: ";
    cin >> user;
    if (user.id == "Q") break;

    if (userTree.Search(user))
      cout << "Valid user\n";
    else
      cout << "Not a valid user\n";
  }
}

