/**********************************************************************
 *
 * vlistbrowserclass.cpp -- 
 * Copyright (C) 1999  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 "vlistbrowserclass.h"
#include "OIDtools.h"
#include "browsetoolsclass.h"
#include "cgiutils.h"


vlistbrowserclass::vlistbrowserclass () {
}

vlistbrowserclass::~vlistbrowserclass () {
}

// returns the name that specifies the browserclass type
text_t vlistbrowserclass::get_browser_name () {
  return "VList";
}

browserclass* vlistbrowserclass::clone()
{
  vlistbrowserclass* browser = new vlistbrowserclass();
  if (browser != NULL) {
#ifdef GSDL_USE_BY_BOOK_MACROS
    browser->m_oByBookMacros.Copy(m_oByBookMacros);
#endif
  }
  return browser;
}

void vlistbrowserclass::load_metadata_defaults (text_tset &metadata) {
  metadata.insert ("haschildren");
  metadata.insert ("doctype");
}

text_t vlistbrowserclass::get_default_formatstring () {
  return "<td valign=\"top\">[link][icon][/link]</td>"
    "<td valign=\"top\">[srclink]{Or}{[thumbicon],[srcicon]}[/srclink]</td>"
    "<td valign=\"top\">[highlight]{Or}{[dls.Title],[dc.Title],[Title],Untitled}[/highlight]"
    "{If}{[Source],<br><i>([dmsafe:Source])</i>}</td>";
}

bool vlistbrowserclass::show_search_result_links(recptproto * collectproto,const text_t &collection,ostream& logout){
     ColInfoResponse_t cinfo;
     comerror_t err;
     collectproto->get_collectinfo (collection, cinfo, err, logout);
     bool show_links = false;

     text_tmap::const_iterator format_here = cinfo.format.begin();
     text_tmap::const_iterator format_end = cinfo.format.end();
     
     while (format_here != format_end) {
       if (((*format_here).first == "DocumentSearchResultLinks") && 
	   ((*format_here).second == "true")){
	 show_links = true;
         break;
       }
       ++format_here;
     } 
     
     return show_links;
}

int vlistbrowserclass::output_section_group(ResultDocInfo_t &section, cgiargsclass &args,
                                            const text_t &collection, int colnumber, 
                                            format_t *formatlistptr, bool use_table, 
                                            text_tset &metadata, bool &getParents, 
                                            recptproto * collectproto, displayclass &disp, 
                                            outconvertclass &outconvert, ostream &textout, 
                                            ostream& logout)
{
  browsetoolsclass btools;
  text_t link, icon;
  text_t collink = collection;
  bool show_links = show_search_result_links(collectproto,collection,logout);


#ifndef DOCHANDLE
  if (!collink.empty()) collink = "&amp;c=" + collink;
#endif

  get_link_icon (section, args, collink, link, icon, show_links);

  //get_link_icon (section, args, collink, link, icon);

  bool highlight = false;
  if (!args["d"].empty()) {
    if (args["d"] == section.OID) highlight = true;
  } else 
    if (args["cl"] == section.OID) highlight = true;


  /* use_table is set to true if the format string starts with <td> */
  if (use_table || colnumber > 0) {
    if (colnumber > 0 ){
      textout << outconvert << "<table id=\"toc_top\" class=\"v_list\"><tr valign=\"top\">";
    }
    else{
      textout << outconvert << "<table id=\"toc_top\" class=\"v_list\"><tr valign=\"top\">";
    }

    // get tab size
    text_t tab; int itab;
    disp.expandstring (displayclass::defaultpackage, "_tabwidth_", tab);
    itab = tab.getint();
    if (colnumber > 0) textout << outconvert << disp 
			       << "<td><img alt=\"\" src=\"_httpiconspace_\" width=\"" 
			       << (itab*colnumber) << "\"/></td>";
  } else {
    textout << outconvert << "<div class=\"v_list\">\n";
  }

  text_tmap options;
  options["link"] = link;
  options["icon"] = icon;
  if (highlight) options["highlight"] = "1";
  else options["highlight"] = "0";
  options["DocImage"] = btools.get_cover_image();
  options["assocfilepath"] = btools.get_assocfile_path();
  textout << outconvert << disp 
	  << get_formatted_string (collection, collectproto, 
				   section, disp, formatlistptr, 
				   options, logout);
  
  if (use_table  || colnumber > 0) {
    textout << outconvert << "</tr></table>\n";
  } else {
    textout << outconvert << "</div>\n";
  }

  return 1;
}

int vlistbrowserclass::output_section_group(FilterResponse_t &sections, cgiargsclass &args,
                                            const text_t &collection, int colnumber, 
                                            format_t *formatlistptr, bool use_table, 
                                            text_tset &/*metadata*/, bool &/*getParents*/, 
                                            recptproto * collectproto, displayclass &disp, 
                                            outconvertclass &outconvert, ostream &textout, 
                                            ostream& logout)
{
  browsetoolsclass btools;
  text_t link, icon;
  text_t &arg_d = args["d"];
  text_t &arg_cl = args["cl"];
  
  text_t collink = collection;
  bool show_links = show_search_result_links(collectproto,collection,logout);

#ifndef DOCHANDLE
  if (!collink.empty()) collink = "&amp;c=" + collink;
#endif

  if (colnumber > 0) {
    textout << outconvert << "<table id=\"tabwidth\"><tr valign=\"top\">";
    // get tab size
    text_t tab; int itab;
    disp.expandstring (displayclass::defaultpackage, "_tabwidth_", tab);
    itab = tab.getint();
    if (colnumber > 0) textout << outconvert << disp 
			       << "<td><img alt=\"\" src=\"_httpiconspace_\" width=\"" 
			       << (itab*colnumber) << "\"/></td>";
    textout << outconvert << "<td>";
  }

  /* use table set to true if format string starts with <td> */
  if (use_table) {
    textout << outconvert << "<table id=\"group_top\" class=\"v_list\">\n";
  } else {
    textout << outconvert << "<div   id=\"group_top\" class=\"v_list\">\n";
  }

  ResultDocInfo_tarray::iterator thissection = sections.docInfo.begin();
  ResultDocInfo_tarray::iterator endsection = sections.docInfo.end();

  // ** here lies Alan's hack to get 4 results per table row
  int item = 0, perline; // set perline to 1 normally
  text_t fstring;

  text_tmap options;
  options["link"] = link;
  options["icon"] = icon;
  options["highlight"] = "0";
  options["DocImage"] = btools.get_cover_image();
  options["assocfilepath"] = btools.get_assocfile_path();

  if ( thissection != endsection ) { // only if there are results (else corrupts display)
    fstring = get_formatted_string (collection, collectproto, *thissection,
                                    disp, formatlistptr, options, logout);
    // if format string
    // has <td><t (e.g. <td><table>) then
    // we assume it is an image and put it in 4 columns
    if (fstring[5] == 't') 
      perline = 4;
    else
      perline = 1;
  }

  int count = 0; 

  while (thissection != endsection) {
    ++item;
    get_link_icon (*thissection, args, collink, link, icon,show_links);
    //get_link_icon (*thissection, args, collink, link, icon);
    bool highlight = false;
    if (!arg_d.empty()) {
      if (arg_d == (*thissection).OID) highlight = true;
    } else 
      if (arg_cl == (*thissection).OID) highlight = true;

    if ((item == 1 && use_table) || colnumber > 0 )
      textout << outconvert << "<tr valign=top>\n";

    options["link"] = link;
    options["icon"] = icon;
    if (highlight) options["highlight"] = "1";
    else options["highlight"] = "0";
    options["DocImage"] = btools.get_cover_image();
    options["assocfilepath"] = btools.get_assocfile_path();

    textout << outconvert << disp 
	    << " " << get_formatted_string (collection, collectproto, *thissection, disp,
					    formatlistptr, options, logout);

    if ((item >= perline && use_table) || colnumber > 0) {
      textout << outconvert << "\n</tr>";
      item = 0;
    }
    textout << outconvert << "\n";
    ++thissection;
  }

  if (use_table)
    textout << outconvert << "</table>\n";
  else
    textout << outconvert << "</div>\n";
  if (colnumber > 0) textout << outconvert << "</td></tr></table>\n";

  return 1;
}


// get_link_icon attempts to work out what type of icon should be displayed for
// the given section and what it should link to.
// [modification to allow default document detach settings -- kjdon]
void vlistbrowserclass::get_link_icon (ResultDocInfo_t &section, cgiargsclass &args,
				       const text_t &collink, text_t &link, text_t &icon, bool showresultlinks) {

 

#ifndef DOCHANDLE
  link = "<a href=\"_httpdocument_" + collink;
#else
  link = "<a href=\"_httpdocumenthandle_(" + collink;
#endif

  text_t link_end = "\">";

#ifndef DOCHANDLE
  text_t detach_link_end = "&amp;x=1\" target=\\_blank>"; // to detach the link, and x=1 signifies it is a detached page
#else
  text_t detach_link_end = "\" target=\\_blank>"; // to detach the link, and x=1 signifies it is a detached page
#endif

  icon = "_document:icontext_";

  text_t doctype;
  int haschildren = 0;

  if (section.metadata.count("haschildren")>0)
    haschildren = section.metadata["haschildren"].values[0].getint();
  if (section.metadata.count("doctype")>0)
    doctype = section.metadata["doctype"].values[0];

  text_t &arg_d = args["d"];
  text_t &arg_cl = args["cl"];

  if (args["a"] == "q")
  {
    // query results list
#ifndef DOCHANDLE
    int result_num = section.result_num;
    int num_docs = args["nmd"].getint();
    int srn = 0;
    int srp = 0;
    if (showresultlinks && result_num < num_docs) {
      srn = result_num  + 1;
    }    
    if (showresultlinks && result_num > 1 ) {
      srp = result_num  - 1;
    }    
        
    text_t srp_t = srp; 
    text_t srn_t = srn; 
    link +="&amp;srp="+srp_t;
    link +="&amp;srn="+srn_t;
    link +="&amp;cl=search&amp;d=" + section.OID;
#else
    link += "," + section.OID+")";
#endif
 
    if (args["xx"] == "1") {
      link += detach_link_end;
    }
    else {
      link += link_end;
    }
    if ((is_top (section.OID)) && (haschildren == 1)) icon = "_document:iconclosedbook_";
    else if (haschildren == 1) icon = "_document:iconclosedfolder_";  
  }
  else if (!arg_d.empty()) {
    // we are in a document - none of the links should be detach links
    if (is_top(section.OID)) {
      // we link back to the originating page eg search page or classifier page
      icon = "_document:iconopenbook_";
      if (arg_cl == "search") { 
	link = "<a href=\"_httpquery_\">";
      }
      else {
#ifndef DOCHANDLE
	link += "&amp;cl=" + arg_cl + "\">";
#else
	link += ","+arg_cl + ")\">";
#endif
      }
    }
    else if (haschildren == 1) {
      if ((args["gc"] == "1") || 
	  (is_child_of (section.OID, arg_d)) ||
	  (section.OID == arg_d)) {
	icon = "_document:iconopenfolder_";
#ifndef DOCHANDLE
	link += "&amp;cl=" + arg_cl + "&amp;d=" + section.OID + ".pr\">";
#else
	link += ","+section.OID + ".pr)\">";
#endif
      }
      else {
	icon = "_document:iconclosedfolder_";
#ifndef DOCHANDLE
	link += "&amp;cl=" + arg_cl + "&amp;d=" + section.OID + "\">";
#else
	link += ","+section.OID + ")\">";
#endif
      }
    }
    else {
      if (args["gt"] == "0") {
#ifndef DOCHANDLE
	link += "&amp;cl=" + arg_cl + "&amp;d=" + section.OID + "\">";
#else
	link += ","+section.OID + ")\">";
#endif
      }
      else {
#ifndef DOCHANDLE
	link += "&amp;cl=" + arg_cl + "&amp;d=" + section.OID + "#" + section.OID + "\">";
#else
	link += ","+section.OID + "#" + section.OID + ")\">";
#endif
      }
    }
  }
  else {
    // classification level - links to docs may be detaching
    if (haschildren == 1) {
      if (doctype == "classify") {
	// Dynamic classifier nodes
	if (args["a"] == "dc")
	{
	  // Parent node or current node
	  text_t classifier_node_dcn = "";
	  if (!starts_with (section.OID, args["dcn"]) || section.OID == args["dcn"])
	  {
	    icon = "_document:iconopenbookshelf_";
	    classifier_node_dcn = section.OID + ".pr";
	  }
	  // Child node
	  else
	  {
	    icon = "_document:iconclosedbookshelf_";
	    classifier_node_dcn = section.OID;
	  }

	  // The node label is going into the URL, so make it CGI-safe
	  text_t classifier_node_dcn_cgi_safe = cgi_safe_utf8(classifier_node_dcn);
	  link = "<a href=\"_gwcgi_?c=" + args["c"] + "&amp;a=dc&amp;dcl=" + args["dcl"] + "&amp;dcn=" + classifier_node_dcn_cgi_safe + "\">";
	}
	// Static classifier nodes
	else if ((args["gc"] == "1") || 
	    (is_child_of (section.OID, arg_cl)) || 
	    (section.OID == arg_cl)) {
	  icon = "_document:iconopenbookshelf_";

#ifndef DOCHANDLE
	  link += "&amp;cl=" + section.OID + ".pr\">";
#else
	  link += ","+section.OID + ".pr)\">";
#endif
	}
	else {
	  icon = "_document:iconclosedbookshelf_";

#ifndef DOCHANDLE
	  link += "&amp;cl=" + section.OID + "\">";
#else
	  link += ","+section.OID + ")\">";
#endif
	}
      }
      else {
	icon = "_document:iconclosedbook_";
#ifndef DOCHANDLE
	link += "&amp;cl=" + arg_cl + "&amp;d=" + section.OID;
#else
	link += ","+section.OID+")";
#endif
	if (args["xx"] == "1") {
	  link +=  detach_link_end;
	}
	else {
	  link += link_end;
	}
      }
    }
    else {
      if (doctype == "classify") link = "";
      else {
#ifndef DOCHANDLE
	link += "&amp;cl=" + arg_cl + "&amp;d=" + section.OID;
#else
	link += "," + section.OID +")";
#endif
	if (args["xx"] == "1") {
	  link +=  detach_link_end;
	}
	else {
	  link += link_end;
	}
      }
    }
  }
}
