// 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 _logger = Cc["@flock.com/logger;1"].createInstance(Ci.flockILogger);
_logger.init("topfeeds");

var _coop = Cc["@flock.com/singleton;1"]
            .getService(Ci.flockISingleton)
            .getSingleton("chrome://flock/content/common/load-faves-coop.js")
            .wrappedJSObject;

var feedManager = Cc["@flock.com/feed-manager;1"]
                  .getService(Ci.flockIFeedManager);

var draggingObserver = {
  onDragStart: function topsites_onDragStart(aEvent, aTransferData, aAction) {
    var url = aEvent.target.getAttribute("url");
    var title = aEvent.target.getAttribute("name");
    if (!url) {
      return;
    }
    aTransferData.data = new TransferData();
    aTransferData.data.addDataForFlavour("text/x-moz-url", url + "\n" + title);
    var link = "<a href='" + url + "'>" + title + "</a>";
    aTransferData.data.addDataForFlavour("text/html", link);
    aTransferData.data.addDataForFlavour("text/unicode", url);
  },
  onDragOver: function topsites_onDragOver(aEvent, aTransferData, aAction) {
  },
  onDrop: function topsites_onDrop(aEvent, aTransferData, aAction) {
  },
  onDragExit: function topsites_onDragExit(aEvent, aTransferData, aAction) {
  }
}

var gTopFeeds = null;

function TopFeeds(aStreamBoxId) {
  this._feedStreamBox = document.getElementById(aStreamBoxId);
  this._newsContext = feedManager.getFeedContext("news");

  var prefs = Cc["@mozilla.org/preferences-service;1"]
              .getService(Ci.nsIPrefBranch);
  this.mMaxCount = prefs.getIntPref("flock.myworld.topfeeds.count");
}

function openFeedHeadline(headlineURL, headlineID, event) {
  if (event.button == 2) {
    return;
  }

  this.gMetrics.report("MyWorld-FeedClick", null);
  var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
           .getService(Ci.nsIWindowMediator);
  var win = wm.getMostRecentWindow("navigator:browser");
  if (win) {
    openURLMyWorld(headlineURL, event, false);

    var coopObj = _coop.get(headlineID);
    coopObj.unseen = false;
  }
}

// Private method used recursively to walk the feed tree
TopFeeds.prototype._updateEachChild =
function TopFeeds__updateEachChild(aFeedFolder) {
  var feedFolderEnum = aFeedFolder.getChildren();
  while (feedFolderEnum.hasMoreElements()) {
    var feedFolderChild = feedFolderEnum.getNext();
    if (feedFolderChild instanceof Ci.flockIFeed) {
      if (this._feedStreamBox.childNodes.length < this.mMaxCount ||
          this._feedStreamBox.lastChild.latestDate < feedFolderChild.getPubDate()) {
        // the feed is new enough
        this.updateFeed(feedFolderChild);
      }
    } else if (feedFolderChild instanceof Ci.flockIFeedFolder) {
      this._updateEachChild(feedFolderChild);
    }
  }
}

TopFeeds.prototype.updateFeed =
function TopFeeds_updateFeed(aFeed) {
  _logger.debug("update " + aFeed.id());
  var url = aFeed.getURL().spec;

  // If it's already there, remove it first from its parent
  var domFeed = document.getElementById(url);
  if (domFeed) {
    this._feedStreamBox.removeChild(domFeed);
  } 
  if (aFeed.getUnreadCount() == 0) {
    return;
  }
  var domFeedCreated = false;
  if (!domFeed) {
    // Create the new DOM node
    domFeedCreated = true;
    domFeed = document.createElement("feedstream");
    domFeed.id = url;
    domFeed.setAttribute("class", "faveFeed");
    domFeed.setAttribute("flex", "1");
    var startDrag = "nsDragAndDrop.startDrag(event, draggingObserver, true);"
    domFeed.setAttribute("ondraggesture", startDrag);
    var favicon = aFeed.getFavicon();
    domFeed.setAttribute("favicon", favicon ? favicon.spec : null);
    domFeed.setAttribute("name", aFeed.getTitle());
    domFeed.setAttribute("url", url);
  }
  domFeed.latestDate = aFeed.getPubDate();

  insertElement(this._feedStreamBox, domFeed);

  if (domFeedCreated) {
    // Send notification for redraw
    var os = Cc["@mozilla.org/observer-service;1"]
             .getService(Ci.nsIObserverService);
    os.notifyObservers(null, "refresh-myworld-size", false);
  }
  setNoItemMessage(this._feedStreamBox, "noFeedsID");
}

TopFeeds.prototype.removeFeed =
function TopFeeds_removeFeed(aFeed) {
  var domFeed = document.getElementById(aFeed.getURL().spec);
  if (domFeed) {
    this._feedStreamBox.removeChild(domFeed);
    domFeed = null;
    setNoItemMessage(this._feedStreamBox, "noFeedsID");
  }
}

TopFeeds.prototype._updateAll =
function TopFeeds_updateAll() {
  var root = this._newsContext.getRoot();
  this._updateEachChild(root);
  cutToMax(this._feedStreamBox, this.mMaxCount);
  setNoItemMessage(this._feedStreamBox, "noFeedsID");
}

// flockIFeedContextObserver
TopFeeds.prototype.onSubscribe =
function TopFeeds_onSubscribe(aContext, aFeed) {
  this.updateFeed(aFeed);
  cutToMax(this._feedStreamBox, this.mMaxCount);
}

// flockIFeedContextObserver
TopFeeds.prototype.onUnsubscribe =
function TopFeeds_onUnsubscribe(aContext, aFeed) {
  this.removeFeed(aFeed);
}

// flockIFeedContextObserver
TopFeeds.prototype.onUnreadCountChange =
function TopFeeds_onUnreadCountChange(aContext, aFeed, aSourceId) {
  if (aFeed) {
    this.updateFeed(aFeed);
    cutToMax(this._feedStreamBox, this.mMaxCount);
  }
}

TopFeeds.prototype.init =
function TopFeeds_init() {
  this._updateAll();
  this._newsContext.addObserver(this);
  gObsrvr = {};
  gObsrvr.observe = function date_observe(aSubject, aTopic, aString) {
    if (aTopic == "refresh-myworld-date") {
      var feedStreamBox = document.getElementById("feedstreambox");
      for (var i = feedStreamBox.childNodes.length - 1; i >= 0; i--) {
        var id = _coop.Feed.get_id({URL: feedStreamBox.childNodes[i].id});
        feedStreamBox.childNodes[i].updateFeedDate(_coop.get(id, true));
      }
      _logger.debug("refreshed Feed Dates");
    }
  }

  // Add observer for time change
  var os = Cc["@mozilla.org/observer-service;1"]
           .getService(Ci.nsIObserverService);
  os.addObserver(gObsrvr, "refresh-myworld-date", false);
}

TopFeeds.prototype.uninit =
function TopFeeds_uninit() {
  this._newsContext.removeObserver(this);
  var os = Cc["@mozilla.org/observer-service;1"]
           .getService(Ci.nsIObserverService);
  os.removeObserver(gObsrvr, "refresh-myworld-date");
}

function onLoad() {
  _logger.debug("onLoad");
  gTopFeeds = new TopFeeds("feedstreambox");
  gTopFeeds.init();
}

function onUnload() {
  if (_logger) {
    _logger.debug("onUnload");
  }

  if (gTopFeeds) {
    gTopFeeds.uninit();
    gTopFeeds = null;
  }
}
