/**********************************************************************
 *
 * metaformat.cpp --
 *
 * Copyright (C) 2004-2010  The New Zealand Digital Library Project
 *
 * A component of the Greenstone digital library software
 * from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *********************************************************************/

#include <fstream>
#include "metaformat.h"
#include "gsdltools.h"
#include "gsdlunicode.h"
#include "recptprototools.h"


metaformat::metaformat()
{
}

text_t metaformat::get_mapping(const text_t &collection, const text_t &collectionField)
{
  if (this->oaiConfigure == NULL) {
    return "";
  }

  return this->oaiConfigure->getMapping(collection, collectionField, this->formatName());
}

void metaformat::output_item(ostream &output, outconvertclass &outconvert, 
			     bool &headerDone, const text_t &label, 
			     const text_tarray &values)
{ 

  if (!headerDone && (values.size() > 0)) {
    this->output_metadata_header(output);
    headerDone = true;
  }

  for (int item = 0; item < values.size(); ++item) {
    if (this->oaiConfigure->getOAIVersion() >= 200) { // TODO: GRB: This code may need to be subclassed by dc for 200 and later...
      output << outconvert << "        <" << this->formatPrefix() << ":" << label << ">" << xml_safe(values[item]) << "</" << this->formatPrefix() << ":" << label << ">\n";
    }
    else {
      output << outconvert << "        <" << label << ">" << xml_safe(values[item]) << "</" << label << ">\n";
    }
  }
}

bool metaformat::output_custom_metadata(ostream &output, outconvertclass &outconvert, bool &headerDone, const text_t &collection, ResultDocInfo_t &docInfo) {
  return false;
}
bool metaformat::scan_metadata(ostream &output, const text_t &collection, ResultDocInfo_t &docInfo,
			       bool doOutput) 
{ 
  bool headerDone = false;
  MetadataInfo_tmap::iterator here = docInfo.metadata.begin();
  MetadataInfo_tmap::iterator end = docInfo.metadata.end();

  utf8outconvertclass utf8convert; // we want to output metadata in utf8

  // metaItem is used initially to identify the rfc1807 (etc) metadata items. It is 
  // then used to hold the name of the metadata item, such as "title" or "subject".
  text_t metaItem;
  text_t::const_iterator start, last; // Use two iterators to go through metaItem

  while (here != end) {
    start = last = here->first.begin();

    if (here->first.size() < this->formatPrefix().size() ||
	here->first[this->formatPrefix().size()] != '.') {
      metaItem == "";
    }
    else {
      last += this->formatPrefix().size(); // Move last so that it is at the
      // '.' 
      metaItem = substr(start, last);          // Gets the substring starting at start and going up to (but
                                               // not including) last. This should be "dc" (for example)
    }

    // Map the element using the "oaimapping" specification from the oai.cfg/collect.cfg files, if defined
    text_t mapTo = this->get_mapping(collection, here->first);
    if (mapTo != "") {
      if (doOutput) {
	if (this->is_valid_element(mapTo)) {
	  this->output_item(output, utf8convert, headerDone, mapTo, here->second.values);
	}
      }
      else {
	if (here->second.values.size() > 0) {
	  return true;
	}
      }
    }

    // Otherwise try to map the element automatically
    // For example, dc.X is mapped to oai_dc.X 
    else if (metaItem == this->formatPrefix()) {
      metaItem = substr(last+1, here->first.end()); // Get the rest of the metadata tag (it's name) but without the '.'
      // remove xxx^ eg Coverage^Spatial becomes spatial
      // this is for qualified dublin core. May affect other sets later if they
      // validly have ^ in them.
      text_t::iterator hat = findchar(metaItem.begin(), metaItem.end(), '^');
      if (hat != metaItem.end()) {
	metaItem = substr(hat+1, metaItem.end());
      }
      lc(metaItem.begin(),metaItem.begin()+1); // We want lowercase, but some of the fields in qualified dublin core have internal upper case, eg instructionalMethod. So we assume that lowercasing the first letter is enough
      if (doOutput) {
	if (this->is_valid_element(metaItem)) {
	  
	  this->output_item(output, utf8convert, headerDone, metaItem, here->second.values);
	}
      }
      else {
	if (here->second.values.size() > 0) {
	  return true;
	}
      }
    }  
    else {
    }

    ++here;
  }

  if (!doOutput) {
    return false;
  }
  // specific metadata formats might need to do some custom metadata that is not just a standard mapping. eg oai_dc outputting an identifier that is a link
  this->output_custom_metadata(output, utf8convert, headerDone, collection, docInfo); 
  if (headerDone) {

    this->output_metadata_footer(output);
  }
  
  return headerDone;
}

text_t metaformat::get_metadata_value(ResultDocInfo_t &docInfo, const text_t &meta_name) {
  MetadataInfo_tmap::iterator here = docInfo.metadata.find(meta_name);
  if (here == docInfo.metadata.end()) {
    return "";
  }
  return here->second.values[0];
  
}

void metaformat::get_metadata_values(ResultDocInfo_t &docInfo, const text_t &meta_name, text_tarray &values) {
  MetadataInfo_tmap::iterator here = docInfo.metadata.find(meta_name);
  if (here != docInfo.metadata.end()) {
    values = here->second.values;
  }
}

bool metaformat::is_available(const text_t &collection, ResultDocInfo_t &docInfo)
{ 
  ofstream o("dummy", ios::out);
  return this->scan_metadata(o, collection, docInfo, false);
}

bool metaformat::is_valid_element(text_t &meta_name)
{
  if (elementSet.count(meta_name)==1) return true;
  return false;
  
}

bool metaformat::output_metadata(ostream &output, const text_t &collection, ResultDocInfo_t &docInfo) 
{ 
  return this->scan_metadata(output, collection, docInfo, true);
}

bool metaformat::output_record(ostream &output, recptproto *protocol, const text_t &collection, 
			       const text_t &OID) 
{
  FilterResponse_t response;
  text_tset        metadata;
  ofstream         logout("oai.log", ios::app);

  // get the document information
  if (!get_info(OID, collection, "", metadata, false, protocol, response, logout)) {
    // TODO: error, bad request
    //   cerr << "Bad identifier or protocol " << OID << endl;
    return false;
  }

  // check to see if it's a classifier
  text_t childHead;
  //  int oaiVersion = this->oaiConfigure->getOAIVersion();
  text_t::const_iterator start = OID.begin();
  text_t::const_iterator here  = OID.begin();
  here += 2;
  childHead = substr(start, here);

  // if it isn't a document, kill it now
  if (childHead == "CL") {
    //    cerr << "Not a document" << endl;
    return false;
  }

  // output record header
  output << "<record>\n";

  // output header part of oai response
  output << "<header>" << endl;
  output << "  <identifier>" << OID << "</identifier>" << endl;
  // TODO: add modified date

  output << "</header>" << endl;

  // output metadata part of oai response
  this->output_metadata(output, collection, response.docInfo[0]);

  // output the description of the document
  //  output << "<about>\n";
  //  output << "</about>\n";

  // close record
  output << "</record>\n";
    
  return true;
}
