#include "CourseCatalog.h"

CourseCatalog::CourseCatalog(void) : 
  coursedb(File("data/courses.db"))
{
  while( coursedb.hasMoreData() ) {
    Course c = Course::parse(coursedb.read());
    pairs.insert(make_pair(c.getCourseNum(),c));
  }
}

CourseCatalog::~CourseCatalog()
{
}

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

inline Course& CourseCatalog::find(string id) {
  return pairs[id];
}

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

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

    // Check the instructor
    if(!found) {
      loc = (c.getInstructor()).find(key,0);
      if( loc != string::npos ) found = true;
    }

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

inline bool CourseCatalog::insert(Course c) {
  map<string,Course>::iterator i = pairs.find(c.getCourseNum());
  if( i != pairs.end() ) {
    return false;
  }
  pairs.insert( make_pair(c.getCourseNum(), c ) );
  coursedb.write(c.toString());
  return true;
}

inline bool CourseCatalog::remove(Course c) {
  remove(c.getCourseNum());
}

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

  coursedb.initialize();

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

inline bool CourseCatalog::replace(string cid, Course c) {
  if( cid != c.getCourseNum()  ) return false;

  remove(cid);
  insert(c);
}

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