/**********************************************************************
 *
 * sqldbclass.cpp -- 
 * Copyright (C) 2010  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 "sqldbclass.h"

sqldbclass::sqldbclass(const text_t& gsdlhome) 
  : dbclass(gsdlhome)
{ 
}

sqldbclass::~sqldbclass()
{
}



// returns array of document OIDs
text_tarray sqldbclass::get_documents_where (const text_t& sql_initial_cmd,
					     const text_t& sort_by)
{
  text_tarray document_OIDs;

  // Get the entries in the "document_metadata" table where the 'sql_cmd'
  // parameter is used to control what is located
  text_t sql_cmd = sql_initial_cmd;

  // If we're sorting the documents by a certain metadata element, extend the SQL command to do this
  if (sort_by != "")
  {
    text_tlist sbterms;
    splitword(sort_by.begin(), sort_by.end(), "/", sbterms);

    text_t tags_in = "";

    while (!sbterms.empty()) {
      text_t tag = sbterms.front();
      sbterms.pop_front();

      if (!tag.empty()) {
	
	if (tag.size()>3 && (substr(tag.begin(), tag.begin()+3) == "ex.")) {
	  tag = substr (tag.begin()+3, tag.end());
	}

	if (!tags_in.empty()) {
	  tags_in += ",";
	}
	
	tags_in += "'" + sql_safe(tag) + "'";
      }
    }

    sql_cmd = "SELECT DISTINCT docOID FROM (" + sql_cmd + ") LEFT JOIN (SELECT docOID,value FROM document_metadata WHERE element IN (" + tags_in + ")) USING (docOID) ORDER by value";
  }

  //cerr << "**** sql cmd = " << sql_cmd << endl;

  // Perform the SQL request
  vector<text_tmap> sql_results;
  if (!sqlgetarray(sql_cmd, sql_results) || sql_results.size() == 0)
  {
    return document_OIDs;
  }

  // Iterate through the documents and add them to the array to be returned
  vector<text_tmap>::iterator sql_results_iterator = sql_results.begin();
  while (sql_results_iterator != sql_results.end())
  {
    text_tmap sql_result = (*sql_results_iterator);
    document_OIDs.push_back(sql_result["docOID"]);
    sql_results_iterator++;
  }

  return document_OIDs;
}


