#include "TextbookCatalog.h"

TextbookCatalog::TextbookCatalog(void) : 
  textbookdb(File("data/texts.db"))
{
  while( textbookdb.hasMoreData() ) {
    Textbook t = Textbook::parse(textbookdb.read());
    pairs.insert(make_pair(t.getISBN(),t));
  }
}

TextbookCatalog::~TextbookCatalog()
{
}

inline bool TextbookCatalog::contains(string isbn) {
  map<string,Textbook>::iterator i = pairs.find(isbn);
  return( i != pairs.end() );
}

inline Textbook& TextbookCatalog::find(string isbn) {
  return pairs[isbn];
}

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

    // Check the title
    loc = (t.getTitle()).find(key,0);
    if( loc != string::npos ) found = true;
    
    // Check the authors
    for(int j = t.getNumAuthors(); j>0 && !found; j--) {
      loc = ((i->second).getAuthor(j)).find(key,0);
      if( loc != string::npos ) found = true;
    }

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

inline bool TextbookCatalog::insert(Textbook t) {
  map<string,Textbook>::iterator i = pairs.find(t.getISBN());
  if( i != pairs.end() ) {
    return false;
  }
  pairs.insert( make_pair(t.getISBN(), t ) );
  textbookdb.write(t.toString());
  return true;
}

inline bool TextbookCatalog::remove(Textbook t) {
  remove(t.getISBN());
}

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

  textbookdb.initialize();

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

inline bool TextbookCatalog::replace(string isbn, Textbook t) {
  if( isbn != t.getISBN()  ) return false;

  remove(isbn);
  insert(t);
}

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