/*
//
//   ADOBE SYSTEMS INCORPORATED
//   Copyright (C) 2000-2003 Adobe Systems Incorporated
//   All rights reserved.
//
//   NOTICE: Adobe permits you to use, modify, and distribute this file
//   in accordance with the terms of the Adobe license agreement
//   accompanying it. If you have received this file from a source other
//   than Adobe, then your use, modification, or distribution of it
//   requires the prior written permission of Adobe.
//
*/

#include "keyList.h"
#include "ASCalls.h"
#include <fstream>

// ctor
keyList::keyList(){
                head  =  NULL;
}

// ctor, with filename
keyList::keyList( const   string  &fileName){
                head  =  NULL;
               this->fileName = fileName;
}

// dtor
keyList::~keyList(){
               Element * tmp = this->head;
                while  (tmp !=  NULL) {
                               tmp = this->head->next;
                                delete  this->head;
                               this->head  = tmp;
               }
}

// fileName is assumed to be in a platform centric form. This method loads from the 
//           (well behaved) file into the data structure. 
void
keyList::importFile( const   string  &fileName){
                const   char * str = fileName.data();
               ifstream keyValueFile(str);
                if  (!keyValueFile.is_open()){
                                // this exception gets raised to the caller
                                ASRaise(ASRegisterErrorString(ErrAlways, "Sample application error: Unable to open key/value file" ));
               }
                string   name, value;
                while  (keyValueFile >> name){
                               keyValueFile >> value;
                               this->insertElement(name,value);
               }
}

// inserts an element into the data structure
void  
keyList::insertElement( const   string  &key,  const   string  &value){
               Element * tmp =  new  Element;
               tmp->key = key;
               tmp->value = value;
               tmp->next = this->head;
               this->head  = tmp;
}

// dumps all the elements to trace. For diagnostic purposes only (otherwise I 
// would overloaded the ostream operator) 
void
keyList::dumpAll(){
               Element * tmp = this->head;
                while  (tmp !=  NULL){
                               cout <<  "k: "  << tmp->key  <<  " v: "  << tmp->value << endl;
                               tmp=tmp->next;
               }
}

// given a key, returns the element associated with it 
string
keyList::lookupElement( const   string  &key){
               Element *tmp =  head;
                while  (tmp !=  NULL){
                                if  (tmp->key==key){
                                                return  tmp->value;
                               }
                               tmp=tmp->next;
               }
                return   "" ;
}