//
// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2008
// http://flock.com
//
// This file may be used under the terms of the
// GNU General Public License Version 2 or later (the "GPL"),
// http://www.gnu.org/licenses/gpl.html
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// END FLOCK GPL
//

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;

const YAHOO_SEARCH_CID         = Components.ID('{88a8b490-d044-4a8b-bb03-1798864ffabf}');

const nsISupports                   = Components.interfaces.nsISupports;
const nsIClassInfo                  = Components.interfaces.nsIClassInfo;
const nsIFactory                    = Components.interfaces.nsIFactory;
const nsIProperties                 = Components.interfaces.nsIProperties;
const nsILocalFile                  = Components.interfaces.nsILocalFile;
const nsIFile                       = Components.interfaces.nsIFile;
const nsIIOService                  = Components.interfaces.nsIIOService;
const nsIFileProtocolHandler        = Components.interfaces.nsIFileProtocolHandler;
const nsIRDFRemoteDataSource        = Components.interfaces.nsIRDFRemoteDataSource;
const nsIRDFDataSource              = Components.interfaces.nsIRDFDataSource;
const flockISearchService           = Components.interfaces.flockISearchService;
const nsIXMLHttpRequest             = Components.interfaces.nsIXMLHttpRequest;

const YAHOO_SEARCH_CONTRACTID       = '@flock.com/?flock-search-yahoo;1';
const DIRECTORY_SERVICE_CONTRACTID  = '@mozilla.org/file/directory_service;1';
const LOCAL_FILE_CONTRACTID         = '@mozilla.org/file/local;1';
const PREFERENCES_CONTRACTID        = '@mozilla.org/preferences-service;1';
const IO_SERVICE_CONTRACTID         = '@mozilla.org/network/io-service;1';
const XMLHTTPREQUEST_CONTRACTID     = '@mozilla.org/xmlextras/xmlhttprequest;1'

const flockIError = Components.interfaces.flockIError;
const FLOCK_ERROR_CONTRACTID = '@flock.com/error;1'

const YAHOO_SEARCH_API_URL = "http://api.search.yahoo.com/WebSearchService/V1/";

function yahooSearchService() {
  var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  var bundle = sbs.createBundle("chrome://flock/locale/search/search.properties");
  this.serviceName = bundle.GetStringFromName("flock.search.api.yahoo");
  var regionBundle = sbs.createBundle("chrome://browser-region/locale/region.properties");
  this.fullResultsUrl = regionBundle
                          .GetStringFromName("showAllSearchRusultsURL");
}

yahooSearchService.prototype.shortName = "yahoo";
yahooSearchService.prototype.icon = "chrome://flock/content/search/yahooIcon.png";
yahooSearchService.prototype.ref = "urn:flock:search:yahoo";

yahooSearchService.prototype.search = function (aQuery, aNumResults, aListener, aDatasource) {
    var inst = this;
    
    var url = YAHOO_SEARCH_API_URL + "webSearch?" 
       + "appid=flock-search"
       + "&query=" + encodeURIComponent(aQuery)
       + "&zip=" 
       + "&start=1&results=" + aNumResults
       + "&fr=flock-search";

    debug(url + " < call\n");
    this.req = Components.classes[XMLHTTPREQUEST_CONTRACTID].createInstance(nsIXMLHttpRequest);
    this.req instanceof Components.interfaces.nsIJSXMLHttpRequest;
    this.req.open('GET', url, true);
    var req = this.req;    
    //debug('request is ' + req + '\n');
    this.req.onreadystatechange = function (aEvt) {
      if(inst.req.readyState == 4) {
          // debug("\nRESPONSE\n" + inst.xmlhttp.responseText);
          try {
              if(req.status == 200 || req.status == 201) {
                 try {
                     //processor(listener, inst);
                     var rdf = inst.readXML(req.responseXML, aDatasource);
                     var numResults = inst.getNumResults(req.responseXML);
                     aListener.foundResults(numResults, rdf, inst.shortName, aQuery);
                 } catch(e) {
                     debug(e + " " + e.lineNumber+"\n");
                 }
              }
              else {
                  var faultString = req.responseText;
                  // listener.onFault(faultString);
              }
          } catch(e) {
              debug(e + " " + e.fileName + " " + e.lineNumber + "\n");
              //listener.onError(inst.ERROR_PARSER);
          }
      }
    }
    
    this.req.send(null);  
}

yahooSearchService.prototype.getNumResults = function (xmlDoc) {
	try {
		var results = xmlDoc.getElementsByTagName("Result"); 
		return results.length;
	} catch (ex) {
	
	}
}

yahooSearchService.prototype.readXML = function (xmlDoc, aDatasource) {
  var unescapeHTML = Cc["@mozilla.org/feed-unescapehtml;1"]
      .getService(Ci.nsIScriptableUnescapeHTML);
  try {
    var resultSet = xmlDoc.getElementsByTagName("ResultSet")[0];                                                              
    var totalResultsAvailable = parseInt(resultSet.getAttribute("totalResultsAvailable"));  
    var totalResultsReturned = parseInt(resultSet.getAttribute("totalResultsReturned"));                                      
    var firstResultPosition = parseInt(resultSet.getAttribute("firstResultPosition"));                                        
    var start = firstResultPosition;                                                                                          
    var end = firstResultPosition + totalResultsReturned - 1;                                                                 
    var results = xmlDoc.getElementsByTagName("Result"); 

    // Create an in-memory datasource
    var rdfService = Components.classes["@mozilla.org/rdf/rdf-service;1"]
        .getService(Components.interfaces.nsIRDFService);
    var rdfContainerUtils = Components.classes["@mozilla.org/rdf/container-utils;1"]
        .getService(Components.interfaces.nsIRDFContainerUtils);
    var rootNode = rdfService.GetResource("urn:flock:search:yahoo");
        
    
    // clear any existing results
    var props=aDatasource.ArcLabelsOut(rootNode);
    while(props.hasMoreElements()){
		var prop=props.getNext();
		var target=aDatasource.GetTarget(rootNode,prop,true);
		try {
		  //target=target.QueryInterface(Components.interfaces.nsIRDFResource);
		  aDatasource.Unassert(rootNode,prop,target)
		}
		catch (e){
			debug ('yahoo error clearing the ds ' + e + '\n');
		}
	}    
    
    rootNode = rdfService.GetResource("urn:flock:search:yahoo"); 
    container = rdfContainerUtils.MakeSeq(aDatasource, rootNode);
    
    // Fill it with the results
    for (var i = 0; i < results.length; i++) { 
        var result = results[i];                                                                                                
        var title = result.getElementsByTagName('Title')[0].firstChild.nodeValue;
        var clickUrl = result.getElementsByTagName('ClickUrl')[0].firstChild.nodeValue;
        var url = result.getElementsByTagName('Url')[0].firstChild.nodeValue;
        var subject = rdfService.GetResource(url);

        var predicate = rdfService.GetResource("http://home.netscape.com/NC-rdf#Name");
        var name = rdfService.GetLiteral(unescapeHTML.unescape(title));                
        aDatasource.Assert(subject, predicate, name, true);

        var predicate = rdfService.GetResource("http://home.netscape.com/NC-rdf#URL");
        var name = rdfService.GetLiteral(url);
        aDatasource.Assert(subject, predicate, name, true);
        
        var predicate = rdfService.GetResource("http://home.netscape.com/NC-rdf#favicon");
        var name = rdfService.GetLiteral(this.icon);
        aDatasource.Assert(subject, predicate, name, true);

        container.AppendElement(subject);
    }

    return aDatasource;
  } catch(exception) {
    debug('Exception occurred while reading XML (i=' + i + '; start=' + start + ';end=' + end + '): ' + exception);
  }
}


yahooSearchService.prototype.flags = nsIClassInfo.SINGLETON;
yahooSearchService.prototype.classDescription = "Yahoo! Search Service";
yahooSearchService.prototype.getInterfaces = function (count) {
    var interfaceList = [flockISearchService, nsIClassInfo];
    count.value = interfaceList.length;
    return interfaceList;
}
yahooSearchService.prototype.getHelperForLanguage = function (count) {return null;}

// the nsISupports implementation
yahooSearchService.prototype.QueryInterface =
function (iid) {
    if (!iid.equals(flockISearchService) && 
        !iid.equals(nsIClassInfo) &&
        !iid.equals(nsISupports))
        throw Components.results.NS_ERROR_NO_INTERFACE;
    if (iid.equals(nsIRDFDataSource) && !this.dataSourceSetup) {
    }
    return this;
}

// Module implementation
var FlockSearchModule = new Object();

FlockSearchModule.registerSelf =
function (compMgr, fileSpec, location, type)
{
    compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);

    compMgr.registerFactoryLocation(YAHOO_SEARCH_CID, 
                                    "Yahoo Search JS Component",
                                    YAHOO_SEARCH_CONTRACTID, 
                                    fileSpec, 
                                    location,
                                    type);
    //necessary category registration
    var catmgr = Components.classes["@mozilla.org/categorymanager;1"]
        .getService (Components.interfaces.nsICategoryManager);
    catmgr.addCategoryEntry('flockISearchService', 'yahoo', YAHOO_SEARCH_CONTRACTID, true, true);
}

FlockSearchModule.getClassObject =
function (compMgr, cid, iid) {
    if (!cid.equals(YAHOO_SEARCH_CID))
        throw Components.results.NS_ERROR_NO_INTERFACE;
    
    if (!iid.equals(Components.interfaces.nsIFactory))
        throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
    
    return SeachServiceFactory;
}

FlockSearchModule.canUnload =
function(compMgr)
{
    return true;
}
    
/* factory object */
var SeachServiceFactory = new Object();

SeachServiceFactory.createInstance =
function (outer, iid) {
    if (outer != null)
        throw Components.results.NS_ERROR_NO_AGGREGATION;
    return (new yahooSearchService()).QueryInterface(iid);
}

/* entrypoint */
function NSGetModule(compMgr, fileSpec) {
    return FlockSearchModule;
}
