//
// 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
//

var feedUtils = {};

feedUtils.loadFeedsFromLocalOPML =
function feedUtils_loadFeedsFromLocalOPML(aURL, aListener, aCtxt) {
  const CC = Components.classes;
  const CI = Components.interfaces;

  var ios = CC["@mozilla.org/network/io-service;1"]
            .getService(CI.nsIIOService);
  var url = ios.newURI(aURL, null, null);

  var fm = CC["@flock.com/feed-manager;1"].getService(CI.flockIFeedManager);
  var newsContext = fm.getFeedContext("news");

  var opmlService = CC["@flock.com/opml-service;1"]
                    .getService(CI.flockIOpmlService);
  opmlService.subscribe(url, newsContext.getRoot(), true, aListener, aCtxt);
}

feedUtils.getURLFromFile =
function feedUtils_getURLFromFile(aFile) {
  const CC = Components.classes;
  const CI = Components.interfaces;

  var ios = CC["@mozilla.org/network/io-service;1"]
            .getService(CI.nsIIOService);
  var fileHandler = ios.getProtocolHandler("file")
                    .QueryInterface(CI.nsIFileProtocolHandler);
  return fileHandler.getURLSpecFromFile(aFile);
}


feedUtils.isValidURL =
function feedUtils_isValidURL(aURL) {
  const CC = Components.classes;
  const CI = Components.interfaces;

  const VALID_SCHEMES = ["http", "https", "file"];

  var ios = CC["@mozilla.org/network/io-service;1"]
            .getService(CI.nsIIOService);
  try {
    var uri = ios.newURI(aURL, null, null);
    return (VALID_SCHEMES.indexOf(uri.scheme) != -1);
  } catch (ex) {
    return false;
  }
}

feedUtils.addFeedURL =
function feedUtils_addFeedURL() {
  window.openDialog("chrome://flock/content/feeds/addFeedUrl.xul",
                    "AddFeedUrl",
                    "modal,centerscreen");
}

feedUtils.importOPML =
function feedUtils_importOPML() {
  window.openDialog("chrome://flock/content/feeds/importOPML.xul",
                    "ImportOPML",
                    "modal,centerscreen");
}

// Borrowed from FlockStringBundleHelpers.jsm#getStringFromBundle()
feedUtils._getStringFromBundle =
function feedUtils__getStringFromBundle(aBundleName, aStringName, aParams) {
  var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
               .getService(Components.interfaces.nsIStringBundleService)
               .createBundle(aBundleName);
  try {
    if (aParams && aParams.length > 0) {
      return bundle.formatStringFromName(aStringName, aParams, aParams.length);
    } else {
      return bundle.GetStringFromName(aStringName);
    }
  } catch (ex) {
    throw ("L10N bug! Request for entity: '" + aStringName + "' "
           + "failed\n" + ex);
  }
};

feedUtils.exportOPML =
function feedUtils_exportOPML() {
  const CC = Components.classes;
  const CI = Components.interfaces;

  var feedsName = "chrome://flock/locale/feeds/feeds.properties";
  var title =
    feedUtils._getStringFromBundle(feedsName, "flock.feed.export.title");
  var filterText =
    feedUtils._getStringFromBundle(feedsName, "flock.feed.export.opmlFiles");
  var defaultFileName =
    feedUtils._getStringFromBundle(feedsName,
                                   "flock.feed.export.defaultFileName");
  var brand =
    feedUtils._getStringFromBundle("chrome://branding/locale/brand.properties",
                                   "brandShortName");
  var opmlTitle = feedUtils._getStringFromBundle(feedsName,
                                                 "flock.feed.export.opmlTitle",
                                                 [brand]);

  var filePicker = CC["@mozilla.org/filepicker;1"]
                   .createInstance(CI.nsIFilePicker);
  filePicker.init(window, title, CI.nsIFilePicker.modeSave);
  filePicker.appendFilter(filterText, "*.opml");
  filePicker.appendFilters(CI.nsIFilePicker.filterAll);
  filePicker.defaultExtension = "opml";
  filePicker.defaultString = defaultFileName + ".opml";

  if (filePicker.show() != CI.nsIFilePicker.returnCancel) {
    var fm = CC["@flock.com/feed-manager;1"].getService(CI.flockIFeedManager);
    var newsContext = fm.getFeedContext("news");

    var opmlService = CC["@flock.com/opml-service;1"]
                      .getService(CI.flockIOpmlService);
    opmlService.export(newsContext.getRoot(), opmlTitle, filePicker.file);
  }
}

feedUtils.selectWebFeedFromAppPane =
function feedUtils_selectWebFeedFromAppPane(aDocument) {
  // The application pane requires a delayed load of the data.
  // Ensure we have a populated list of data before we examine it.
  var timer = Components.classes["@mozilla.org/timer;1"]
              .createInstance(Components.interfaces.nsITimer);
  timer.initWithCallback({
    notify: function selectWebFeedFromAppPane_notify() {
      var view = aDocument.getElementById("handlersView");
      if (view) {
        var webFeed = view.getElementsByAttribute("type",
                                                  "application/vnd.mozilla.maybe.feed");
        if (webFeed && webFeed[0]) {
          // We have found the "Web feed" item, let's scroll to its index and
          // select the it so show the user where it can be changed
          var richlistitem = webFeed[0];
          var itemIndex = view.getIndexOfItem(richlistitem);
          view.scrollToIndex(itemIndex);
          view.focus();
          view.selectItem(richlistitem);
        }
      }
    }
  }, 50, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
};

/*
 * Launch the preference panel with the applications pane selected by default
 * in order to show the user where to change their feed reader preferences.
 * @param aIsBrowserWindow - If the element actioning this function is/isn't
 * a browser window and not a dialog.
 */
feedUtils.editFeedReader =
function feedUtils_editFeedReader(aIsBrowserWindow) {
  // MBL: Hack to temporarily disable the instantApply preference so that we
  // can set the feed reader selection onLoad.  Since instantApply = true
  // means that we block on the openPreferences call, preventing us from
  // making the selection automatically (without touching upstream code)
  var prefSvc = Components.classes["@mozilla.org/preferences-service;1"]
                          .getService(Components.interfaces.nsIPrefBranch);

  var instantApply = prefSvc.getBoolPref("browser.preferences.instantApply", false);
  if (!instantApply) {
    prefSvc.setBoolPref("browser.preferences.instantApply", true);
  }

  // Open the applications pref pane
  var win = openPreferences("paneApplications");

  // Restore the old preference.
  if (!instantApply) {
    prefSvc.setBoolPref("browser.preferences.instantApply", false);
  }

  if (aIsBrowserWindow) {
    win.onload = function openWebFeedApplication_onLoad() {
      feedUtils.selectWebFeedFromAppPane(this.document);
    };
    return;
  }
  // Load the document in question
  if (document) {
    feedUtils.selectWebFeedFromAppPane(document);
  }
};
