// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2009
// 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 TWITTER_LIVE_SEARCH_NAME = "Twitter";
const TWITTER_LIVE_SEARCH_CLASSID =
  Components.ID("{9846b490-8536-4a8b-bb03-1798864ffabf}");

// API docs: http://apiwiki.twitter.com/Search-API-Documentation?SearchFor=search&sp=1

const CC = Components.classes;
const CI = Components.interfaces;
const CU = Components.utils;

CU.import("resource:///modules/FlockLiveSearchProvider.jsm");

function TwitterLiveSearch() {
  this._init();
}

TwitterLiveSearch.prototype = FlockLiveSearchProvider.generateComponent(
  TWITTER_LIVE_SEARCH_NAME,
  TWITTER_LIVE_SEARCH_CLASSID,
  TwitterLiveSearch,
  "Twitter"
);

TwitterLiveSearch.prototype._getResults =
function TLS__getResults(aXHR, aMaxResults) {
  var results = [];
  var unescapeHTML = CC["@mozilla.org/feed-unescapehtml;1"]
                     .getService(CI.nsIScriptableUnescapeHTML);

  try {
    var nsJSON = CC["@mozilla.org/dom/json;1"].createInstance(CI.nsIJSON);
    var data = nsJSON.decode(aXHR.responseText);
    for each (var result in data.results) {
      results.push({ title: unescapeHTML.unescape(result.text),
                     icon: result.profile_image_url,
                     url: "http://twitter.com/" + result.from_user });
    }
  } catch (ex) {
    // just ignore errors
  }

  return results;
}

var NSGetModule =
  FlockLiveSearchProvider.generateNSGetModule(TWITTER_LIVE_SEARCH_NAME,
                                              TwitterLiveSearch);
