//
// 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 EBAY_SEARCH_CID         = Components.ID('{46a6a8b0-3327-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 EBAY_SEARCH_CONTRACTID  = '@flock.com/?flock-search-ebay;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 EBAY_SEARCH_API_URL = "http://rest.api.ebay.com/restapi";
const EBAY_USERNAME = "flocknflow";
const REST_API_TOKEN = "jCu2LHQ247Q%3D**pWWu%2BOldh2Bj13OcHs1ZZcSytoI%3D";

// The following codes are passed to the api so that flock 
// recieves commisions
const EBAY_AFFILIATE_TRACKING_PARTNER_CODE = "1";
const EBAY_AFFILIATE_TRACKINGID = "2500336";

//const EBAY_API_KEY = "2dd47dbb72b25cc7130a450255af779b";

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

ebaySearchService.prototype.shortName = "ebay";
ebaySearchService.prototype.icon = "chrome://flock/content/search/ebayIcon.png";
ebaySearchService.prototype.ref = "urn:flock:search:ebay";

ebaySearchService.prototype.search = function (aQuery, aNumResults, aListener, aDatasource) {
    var inst = this;
    
    if (!aQuery.length) return;
    
    var url = EBAY_SEARCH_API_URL + "?" 
       + "CallName=GetSearchResults"
       + "&RequestUserId=" + EBAY_USERNAME
       + "&RequestToken=" + REST_API_TOKEN
       + "&Version=491"
       + "&UnifiedInput=1"
       + "&Query=" + encodeURIComponent(aQuery)
       + "&TrackingPartnerCode=" + EBAY_AFFILIATE_TRACKING_PARTNER_CODE
       + "&TrackingID=" + EBAY_AFFILIATE_TRACKINGID;
       
    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;    
    this.req.onreadystatechange = function (aEvt) {
      if(inst.req.readyState == 4) {
          //debug("\nRESPONSE\n" + inst.req.responseText);
          try {
              if(req.status == 200 || req.status == 201) {
                 try {
                     //processor(listener, inst);
                     var rdf = inst.readXML(req.responseXML, aNumResults, 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);  
}

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

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

    // 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:ebay");
    
    // 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 ('ebay error clearing the ds ' + e + '\n');
		}
	}        
        
    // Fill it with the results
    rootNode = rdfService.GetResource("urn:flock:search:ebay");
    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('ViewItemURL')[0].firstChild.nodeValue;
        var url = result.getElementsByTagName('ViewItemURL')[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('ebaySearchService ' + ex + '\n');
  }
}


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

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

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

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