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

/* Program to validate 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
 ********************************************************************/

//--- Class containing user information ----------------//
//    with >>, ==, <, and > operators
class UserInfo
{
 public: // ***** function members and friends ***** //
  // -- id accessor
  string id() const { return myId; }

  //--- input op erator
  friend istream & operator>>(istream & in, UserInfo & user);

  //--- equals operator
  bool operator==(const UserInfo & user) const
  { return myId == user.myId &&
           myPassword == user.myPassword; }

  //--- less-than operator
  bool operator<(const UserInfo & user) const
  { return myId < user.myId; }

  //--- greater-than operator
  bool operator>(const UserInfo & user) const
  { return myId > user.myId; }

 private: // ***** data members ***** //
  string myId,
         myPassword;
};

//--- Definition of input operator
istream & operator>>(istream & in, UserInfo & user)
{
  in >> user.myId>> user.myPassword;
  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
  while (!userFile.eof())
  {
     userFile >> user;
     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";
  }
}

