#include "StudentCatalog.h"

StudentCatalog::StudentCatalog(void) : 
  studentdb(File("data/students.db"))
{
  while( studentdb.hasMoreData() ) {
    Student s = Student::parse(studentdb.read());
    pairs.insert(make_pair(s.getID(),s));
  }
}

StudentCatalog::~StudentCatalog()
{
}

inline bool StudentCatalog::contains(string id) {
  map<string,Student>::iterator i = pairs.find(id);
  return( i != pairs.end() );
}

inline Student& StudentCatalog::find(string id) {
  return pairs[id];
}

vector<Student> StudentCatalog::search(string key)
{
  vector<Student> v;
  map<string,Student>::iterator i;
  int loc;
  bool found = false;
  for(i = pairs.begin(); i!= pairs.end(); i++) {
    Student s = i->second;

    // Check the name
    if(!found) {
    loc = (s.getName()).find(key,0);
    if( loc != string::npos ) found = true;
    }

    // FOUND
    if( loc != string::npos ) {
      v.push_back(s);
      cout << " F O U N D " << endl;
      cout << s << endl;
    }
    found = false;
  }
  return v;  
}

inline bool StudentCatalog::insert(Student s) {
  map<string,Student>::iterator i = pairs.find(s.getID());
  if( i != pairs.end() ) {
    return false;
  }
  pairs.insert( make_pair(s.getID(), s ) );
  studentdb.write(s.toString());
  return true;
}

inline bool StudentCatalog::remove(Student s) {
  remove(s.getID());
}

inline bool StudentCatalog::remove(string cid) {
  map<string,Student>::iterator i = pairs.find(cid);
  if( i != pairs.end() ) {
    cout << "Removing " << i->first << endl;
    pairs.erase( i );
  }

  studentdb.initialize();

  for(i = pairs.begin(); i!= pairs.end(); i++) {
    studentdb.write((i->second).toString());
  }
}

inline bool StudentCatalog::replace(string cid, Student s) {
  if( cid != s.getID()  ) return false;

  remove(cid);
  insert(s);
}

float StudentCatalog::computeAvgGPA(void) {
  float sum = 0;
  int count = 0;
  map<string,Student>::iterator i = pairs.begin();
  if( i != pairs.end() ) {
    sum += (i->second).getGPA();
    count++; i++;
  }
  return(sum/count);
}

ostream& operator << (ostream& out, StudentCatalog& sc)
{
  map<string,Student>::iterator i;
  cout << "   Key    -          Value  " << endl;
  for(i = sc.pairs.begin(); i!= sc.pairs.end(); i++) {
    out << i->first << "  " << (i->second).getName() << endl;
  }
  return out;  
}
