#include <iostream> // basic i/o
#include <cstdlib> // rand() and srand()
#include <ctime> // system time
#include <string>
#include <fstream>
#define MAX_HOUSE_SIZE 10
using namespace std;

struct Student{
  string lastname = "";
  string firstname = "";
  string house = "";
};

struct House{
  string name = "";
  unsigned number = 0;
  Student members[MAX_HOUSE_SIZE];
};

House addStudent(Student s, House h){
  if(h.number < MAX_HOUSE_SIZE){
    h.members[h.number] = s;
    h.number++;
  }else{
    cout << "ERROR: House is full.\n";
  }
  return h;
}

int main() {
  Student students[40];
  House houses[4];
  string houseNames[] = {
    "Gryffindor",
    "Hufflepuff",
    "Ravenclaw",
    "Slytherin"
  };

  cout << "Houses:\n";
  for(int i=0; i < 4; i++){
    houses[i].name = houseNames[i];
    cout << houses[i].name << ": " << houses[i].number << endl;
  }

  string temp;
  ifstream infile;
  string filename = "students.csv";
  int num = 0;
  int houseNum;
  bool validHouse;
  
  // seed the PRNG
  unsigned seed;
  seed = time(0);
  srand(seed);

  // Get the filename from the user
  cout << "Please enter the filename: ";
  cin >> filename;

  // Open the file the user specified
  infile.open(filename);

  // If the file successfully opened, process it.
  if(infile){
    // Read the members from the file and display them.
    while (num < 30){
      // getline(string, token, delimiter);
      getline(infile, temp, ',');
      if(temp==""){
        break;
      }
      students[num].lastname = temp;
      getline(infile, temp);
      students[num].firstname = temp;
      cout << num+1 << "). " << students[num].firstname << " " << students[num].lastname << ": ";
      do{
        validHouse = false;
        houseNum = rand() % 4;
        // only add the student if there's room
        if(houses[houseNum].number < MAX_HOUSE_SIZE){
          students[num].house = houseNames[houseNum];
          validHouse = true;
          houses[houseNum] = addStudent(students[num], houses[houseNum]);
        }
        // if the house is full, choose another!
      }while(not validHouse);
      cout << students[num].house << endl;
      num++;
    }
    // Close the file.
    infile.close();
  }else{
    // Display an error message.
    cout << "Error opening " << filename << ".\n";
  }
  for(int x = 0; x < 4; x++){
    cout << "\n" << houses[x].name << ": [" << houses[x].number << "]\n";
    for(int y=0; y < houses[x].number; y++){
      cout << "\n" << y+1 << "). " << houses[x].members[y].lastname << ", " << houses[x].members[y].firstname;
    }
    cout << endl;
  }
  cout << "\n******************\nThe total is: " << num << endl;
  return 0;
}
