//
// 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 CRAIGSLIST_SEARCH_CID         = Components.ID('{67a9e610-313f-11db-a98b-0800200c9a66}');

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 CRAIGSLIST_SEARCH_CONTRACTID  = '@flock.com/?flock-search-craigslist;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 CC = Components.classes;
const CI = Components.interfaces;
const flockIError = Components.interfaces.flockIError;
const FLOCK_ERROR_CONTRACTID = '@flock.com/error;1'

const CRAIGSLIST_SEARCH_API_URL = "http://www.craigslist.org/cgi-bin/search";
//const CRAIGSLIST_API_KEY = "2dd47dbb72b25cc7130a450255af779b";

function craigslistSearchService() {
  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.craigslist");
}

craigslistSearchService.prototype.shortName = "craigslist";
craigslistSearchService.prototype.icon = "http://craigslist.com/favicon.ico";
craigslistSearchService.prototype.ref = "urn:flock:search:craigslist";
craigslistSearchService.prototype.fullResultsUrl = "http://craigslist.org/search/sss?query=";

craigslistSearchService.prototype.search = function (aQuery, aNumResults, aListener, aDatasource) {
    var inst = this;
    
    if (!aQuery.length) return;
    var url = CRAIGSLIST_SEARCH_API_URL + "?" 
       + "areaID=1"
       + "&query=" + aQuery
       + "&catAbbreviation=sss"
       + "&format=rss"

    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) {
          try {
              if(req.status == 200 || req.status == 201) {
                 try {
                     var domParser = CC["@mozilla.org/xmlextras/domparser;1"]
                                     .createInstance(CI.nsIDOMParser);
                     var xmlDoc = domParser.parseFromString(req.responseText,
                                                            "text/xml");
                     var rdf = inst.readXML(xmlDoc, aNumResults, aDatasource);
                     var numResults = inst.getNumResults(xmlDoc);
                     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);  
}

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

craigslistSearchService.prototype.readXML = function (xmlDoc, aMaxResults, aDatasource) {
  try {                                                     
    var results = xmlDoc.getElementsByTagName("item"); 

    // Create an in-memory datasource
    var rdfService = Components.classes["@mozilla.org/rdf/rdf-service;1"]
        .getService(Components.interfaces.nsIRDFService);
    //var rdf = Components.classes["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].createInstance(Components.interfaces.nsIRDFDataSource);
    var rdfContainerUtils = Components.classes["@mozilla.org/rdf/container-utils;1"]
        .getService(Components.interfaces.nsIRDFContainerUtils);
        
    var rootNode = rdfService.GetResource("urn:flock:search:craigslist");
    
    // 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');
		}
	}        
        
        
    // Fill it with the results
    rootNode = rdfService.GetResource("urn:flock:search:craigslist");
    var container = rdfContainerUtils.MakeSeq(aDatasource, rootNode);
    
    var maxResults = (results.length < aMaxResults) ? results.length : aMaxResults;
    for (var i = 0; i < maxResults; i++) { 
        var result = results[i];                                                                                                
        var title = result.getElementsByTagName('title')[0].firstChild.nodeValue;
        var clickUrl = result.getElementsByTagName('link')[0].firstChild.nodeValue;
        var url = result.getElementsByTagName('link')[0].firstChild.nodeValue;
        var subject = rdfService.GetResource(url);

        var predicate = rdfService.GetResource("http://home.netscape.com/NC-rdf#Name");
        var name = rdfService.GetLiteral(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(ex) {
    debug('craigslistSearchService ' + ex + '\n');
  }
}


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

// the nsISupports implementation
craigslistSearchService.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(CRAIGSLIST_SEARCH_CID, 
                                    "craigslist Search JS Component",
                                    CRAIGSLIST_SEARCH_CONTRACTID, 
                                    fileSpec, 
                                    location,
                                    type);
    //necessary category registration
    var catmgr = Components.classes["@mozilla.org/categorymanager;1"]
        .getService (Components.interfaces.nsICategoryManager);
    catmgr.addCategoryEntry('flockISearchService', 'craigslist', CRAIGSLIST_SEARCH_CONTRACTID, true, true);
}

FlockSearchModule.getClassObject =
function (compMgr, cid, iid) {
    if (!cid.equals(CRAIGSLIST_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 craigslistSearchService()).QueryInterface(iid);
}

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