// 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("topsites");

var historyService = Cc["@mozilla.org/browser/nav-history-service;1"]
                     .getService(Ci.nsINavHistoryService);

var gHistoryController;
var gHistoryResult;

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) {
  }
}


function onLoad() {
  gHistoryController = new HistoryController();

  // Get the result from the history service
  var query = historyService.getNewQuery();
  query.onlyBookmarked = true;
  var options = historyService.getNewQueryOptions();
  options.sortingMode = Ci.nsINavHistoryQueryOptions
                          .SORT_BY_VISITCOUNT_DESCENDING;
  options.maxResults = 15;
  gHistoryResult = historyService.executeQuery(query, options);

  // Populate the UI with the initial results
  gHistoryResult.root.containerOpen = true;
  gHistoryController.rebuild();

  // Set an observer so we catch changes on the result set
  gHistoryResult.viewer = historyResultViewer;
}

function HistoryController() {
  this.container = document.getElementById("sitestreambox");

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

// Append an item at the end, ignoring sorting
// Only call that at the beginning, when results are already sorted
HistoryController.prototype.rebuild =
function HistoryController_rebuild() {
  while (this.container.firstChild) {
    this.container.removeChild(this.container.firstChild);
  }

  for (var i = 0; i < gHistoryResult.root.childCount; i++) {
    if (i >= this.mMaxCount) {
      break;
    }

    var node = gHistoryResult.root.getChild(i);

    var siteEntry = document.createElement("sitestream");
    siteEntry.setAttribute("class", "faveSite");
    siteEntry.setAttribute("crop", "end");
    siteEntry.setAttribute("flex", "1");
    if (node.icon) {
      siteEntry.setAttribute("favicon", node.icon.spec);
    }
    siteEntry.setAttribute("name", node.title);
    siteEntry.setAttribute("url", node.uri);
    var startDrag = "nsDragAndDrop.startDrag(event, draggingObserver, true);"
    siteEntry.setAttribute("ondraggesture", startDrag);

    this.container.appendChild(siteEntry);
  }

  var showDiscovery = false;
  if (!this.container.firstChild) {
    showDiscovery = true;
  }

  // Show/Hide discovery text
  document.getElementById("noSites-message")
          .setAttribute("hidden",
                        (showDiscovery ? "false" : "true"));

  var os = Cc["@mozilla.org/observer-service;1"]
           .getService(Ci.nsIObserverService);
  os.notifyObservers(null, "refresh-myworld-size", false);
}

var historyResultViewer = {
  addViewObserver: function hrv_addViewObserver(observer, ownsWeak) {
  },
  itemInserted: function hrv_itemInserted(parent, item, newIndex) {
    // XXX TODO: Be smart and only change what changed
    gHistoryController.rebuild();
  },
  itemRemoved: function hrv_itemRemoved(parent, item, oldIndex) {
    // XXX TODO: Be smart and only change what changed
    gHistoryController.rebuild();
  },
  itemChanged: function hrv_itemChanged(item) {
    // XXX TODO: Be smart and only change what changed
    gHistoryController.rebuild();
  },
  itemReplaced: function hrv_itemReplaced(parent, oldItem, newItem, index) {
    // XXX TODO: Be smart and only change what changed
    gHistoryController.rebuild();
  },
  containerOpened: function hrv_containerOpened(item) {
  },
  containerClosed: function hrv_containerClosed(item) {
  },
  invalidateContainer: function hrv_invalidateContainer(item) {
  },
  invalidateAll: function hrv_invalidateAll() {
    // XXX TODO: Be smart and only change what changed
    gHistoryController.rebuild();
  },
  removeViewObserver: function hrv_removeViewObserver(observer) {
  },
  sortingChanged: function hrv_sortingChanged(sortingMode) {
    // XXX TODO: Be smart and only change what changed
    gHistoryController.rebuild();
  }
};

function onUnload() {
  if (gHistoryResult) {
    gHistoryResult.viewer = null;
    gHistoryResult = null;
  }
}
