// 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 CC = Components.classes;
const CI = Components.interfaces;

const TRIM_BASE_URL = "http://trim.li/api.php"
const TRIM_QUERY = "url="

var EXPORTED_SYMBOLS = ["FlockURLUtils"];

var FlockURLUtils = {

  shorten: function FlockURLUtils_shorten(aURL,
                                          aService,
                                          aSource,
                                          aFlockListener)
  {

    var hr = CC["@mozilla.org/xmlextras/xmlhttprequest;1"]
               .createInstance(CI.nsIXMLHttpRequest)
               .QueryInterface(CI.nsIJSXMLHttpRequest);

    var inst = this;

    inst.metrics = CC["@flock.com/metrics-service;1"]
                   .getService(CI.flockIMetricsService);
    inst._service = aService;
    inst._source = aSource;

    hr.onreadystatechange = function hr_function(aEvent) {
      if (hr.readyState == 4) {

        if (Math.floor(hr.status / 100) == 2) {
          var result = hr.responseText;

          if (result && result.indexOf("null") != 0) {
            // Grab new URL and set it to urlShortened
            var urlData = CC["@mozilla.org/hash-property-bag;1"]
                            .createInstance(CI.nsIWritablePropertyBag2);
            urlData.setPropertyAsAString("url", result);
            urlData.setPropertyAsAString("originalURL", aURL);

            // Report metrics
            inst.metrics.report("Util-UrlShorten",
                                [{service: inst._service,
                                source: inst._source,
                                success: 1}]);

            aFlockListener.onSuccess(urlData, null);
          } else {
            // Report metrics
            inst.metrics.report("Util-UrlShorten",
                                [{service: inst._service,
                                source: inst._source,
                                success: 0}]);

            aFlockListener.onError(null, null);
          }
        } else {
          // Report metrics
          inst.metrics.report("Util-UrlShorten",
                              [{service: inst._service,
                              source: inst._source,
                              success: 0}]);

          // HTTP errors (0 for connection lost)
          aFlockListener.onError(null, null);
        }
      }
    };

    // Hardcode tr.im for now
    var url = TRIM_BASE_URL;
    hr.mozBackgroundRequest = true;
    hr.open('POST', url, true);
    hr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    hr.send(TRIM_QUERY + aURL);
  },

  // Given a shortened URL, determine the destination URL
  unshorten: function FlockURLUtils_unshorten(aURL, aFlockListener) {
    var xhr = CC["@mozilla.org/xmlextras/xmlhttprequest;1"]
              .createInstance(CI.nsIXMLHttpRequest);
    xhr.open("GET", aURL);
    xhr.onreadystatechange = function unshorten_onreadystatechange(aEvent) {
      if (xhr.readyState == 3) {
        var destinationURL = xhr.channel.URI.spec;
        if (destinationURL.indexOf(aURL) == 0) {
          aFlockListener.onError(null, destinationURL);
        } else {
          var urlData = CC["@mozilla.org/hash-property-bag;1"]
                        .createInstance(CI.nsIWritablePropertyBag2);
          urlData.setPropertyAsAString("shortURL", aURL);
          urlData.setPropertyAsAString("destinationURL", destinationURL);
          urlData.setPropertyAsAString("redirect", aURL + " -> " + destinationURL);
          aFlockListener.onSuccess(urlData, destinationURL);
        }
        xhr.abort();
      }
    };
    xhr.send(null);
  },

  hoverLink: function FlockURLUtils_hoverLink(aLinkNode, aSetStatusFunc) {
    if (!aLinkNode.hasAttribute("unshortened")) {
      var unshortenListener = {
        onSuccess: function unshortenListener_onSuccess(aSubject, aTopic) {
          aLinkNode.setAttribute("unshortened", "true");
          aLinkNode.setAttribute("destURL",
                                 aSubject.getPropertyAsAString("destinationURL"));
          var newStatus = aSubject.getPropertyAsAString("redirect");
          aLinkNode.setAttribute("status", newStatus);
          aSetStatusFunc(newStatus);
        },
        onError: function unshortenListener_onError(aError, aTopic) {
        }
      };
      var origURL = aLinkNode.getAttribute("origURL");
      aSetStatusFunc(origURL);
      FlockURLUtils.unshorten(origURL, unshortenListener);
    } else {
      aSetStatusFunc(aLinkNode.getAttribute("status"));
    }
  }

};
