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

// This file contains functions used
// both in the browser context and in the mediabar context

var FlockMedia = {};

FlockMedia.XUL_NAMESPACE = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

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

FlockMedia.getUploadSvc =
function FlockMedia_getUploadService() {
  if (!this._uploadSvc) {
    this._uploadSvc = Components.classes["@flock.com/media/upload-service;1"]
                      .getService(Components.interfaces.flockIPhotoUploadService);
  }
  return this._uploadSvc;
};

FlockMedia.getLogger =
function FlockMedia_getLogger() {
  if (!this._logger) {
    this._logger = Components.classes["@flock.com/logger;1"]
                   .createInstance(Components.interfaces.flockILogger);
    this._logger.init("photo.util");
  }
  return this._logger;
};

FlockMedia.loadFromId =
function FlockMedia_loadFromId(aId, aIsHistoryNav) {
  if (mediabar) {
    // We're in the browser context
    mediabar.loadFromId(aId);
  } else {
    // We're in the mediabar context
    gPhotoDrawer.loadFromId(aId, aIsHistoryNav);
  }
}

// aMenuPopup: the XUL menupopup to insert the elements
// aURN: the Coop URN of the media queries root
// aReferenceNode: an existing node; new nodes will be inserted before
//                 this one. May be null.
FlockMedia.addMediaStreams =
function FlockMedia_addMediaStreams(aDOMNode,
                                    aUrn,
                                    aReferenceNode)
{
  // Clean the menupopup to refresh its contents
  function _cleanMenu(aDOMNode) {
    if (aReferenceNode) {
      var sibling = aReferenceNode.previousSibling;
      var parent = aReferenceNode.parentNode;
      var removeNodes = [];
      while (sibling) {
        if (sibling.getAttribute("mediaquery") == "true") {
          removeNodes.push(sibling);
        }
        sibling = sibling.previousSibling;
      }
      for each (var remove in removeNodes) {
        parent.removeChild(remove);
      }
    } else {
      while (aDOMNode.childNodes.length > 0) {
        aDOMNode.removeChild(aDOMNode.lastChild);
      }
    }
  };
  _cleanMenu(aDOMNode);

  // This function is provided to initialize the main channel popup with
  // a root level of favorited media streams, instead of within a folder itself
  function _insertNode(aItem) {
    if (aReferenceNode) {
      aDOMNode.insertBefore(aItem, aReferenceNode);
    } else {
      aDOMNode.appendChild(aItem);
    }
  };

  var mediaQueries = this._coop.get(unescape(aUrn));
  var childEnum = mediaQueries.children.enumerate();
  while (childEnum.hasMoreElements()) {
    var coopObj = childEnum.getNext();
    // Escape the coopId
    var escCoopId = escape(coopObj.id());
    if (coopObj.isA(this._coop.Folder)) {
      // Append a Folder with possible child elements for display
      var menu = document.createElementNS(this.XUL_NAMESPACE, "menu");
      menu.setAttribute("label", coopObj.name);
      menu.setAttribute("tooltiptext", coopObj.name);
      menu.setAttribute("class", "menu-iconic media-folder");
      menu.setAttribute("mediaquery", "true");
      var menupopup = document.createElementNS(this.XUL_NAMESPACE, "menupopup");
      // Recursively iterate through child elements when required
      menupopup.setAttribute("onpopupshowing",
                "FlockMedia.addMediaStreams(this, '" + escCoopId + "', null);"
              + "event.stopPropagation();");
      menu.appendChild(menupopup);
      _insertNode(menu);
    } else {
      // Append a favorited media stream item to be displayed
      var menuitem = document.createElementNS(this.XUL_NAMESPACE, "menuitem");
      // Check for new items
      var itemName = coopObj.name;
      var cssClass = "";
      if (coopObj.hasUnseenItems) {
        itemName += " " + flockGetString("photo/mediabar",
                                         "flock.media.favs.new");
        cssClass = "newMediaItem";
      }
      menuitem.setAttribute("label", itemName);
      menuitem.setAttribute("tooltiptext", coopObj.name);
      menuitem.setAttribute("mediaquery", "true");
      if (coopObj.favicon) {
        menuitem.setAttribute("image", coopObj.favicon);
        // If we've already assigned a css class separate them with a space
        if (cssClass.length) {
          cssClass += " ";
        }
        cssClass += "menuitem-iconic";
        menuitem.setAttribute("class", cssClass);
        menuitem.setAttribute("oncommand",
                              "FlockMedia.loadFromId('" + escCoopId + "', false);");
      }
      _insertNode(menuitem);
     }
  }

  FlockMedia.showEmptyItem(aDOMNode);
}

FlockMedia.showEmptyItem =
function FlockMedia_showEmptyItem(popup) {
  if (popup.childNodes.length <= 0) {
    var empty = document.createElement("menuitem");
    var label = PlacesUIUtils.getString("bookmarksMenuEmptyFolder");
    empty.setAttribute("label", label);
    empty.setAttribute("disabled", true);
    empty.setAttribute("flockEmpty", true);
    popup.appendChild(empty);
  } else {
    var children = popup.childNodes;
    for each(var child in children.length) {
      if (child.getAttribute("flockEmpty")) {
        popup.removeChild(child);
      }
    }
  }
}

FlockMedia.contextUpload =
function FlockMedia_contextUpload() {
  // If there is no account, offer to configure one now
  if (!FlockMedia.getUploadSvc().hasOnePhotoAccount()) {
    FlockMedia.getUploadSvc().promptForAccount();
    return;
  }

  var node = window.document.popupNode;
  var contentDetector = new nsContentDetector();
  contentDetector.setTarget(node);

  var photoUrls = [];
  photoUrls[0] = contentDetector.imageURL;
  var dropProcessor = new PhotoDropProcessor(photoUrls, null);
  dropProcessor.start();
  FlockMedia.getUploadSvc().launchUploader();
};

FlockMedia.getStringBundle =
function FlockMedia_getStringBundle() {
  var localeService =
    Components.classes["@mozilla.org/intl/nslocaleservice;1"]
              .getService(Components.interfaces.nsILocaleService);
  var stringBundleService =
    Components.classes["@mozilla.org/intl/stringbundle;1"]
              .getService(Components.interfaces.nsIStringBundleService);
  var stringBundle =
    stringBundleService.createBundle("chrome://flock/locale/photo/photo.properties",
                                     localeService.getApplicationLocale());
  return stringBundle;
};

FlockMedia.isAPhoto =
function FlockMedia_isAPhoto(aURL) {
  if (aURL.indexOf("file") != 0) {
    return false;
  }
  var lc = aURL.toLowerCase();
  return ((lc.match(/.+\.jpe?g$/)) ||
          (lc.match(/.+\.png$/)) ||
          (lc.match(/.+\.gif$/)) ||
          (lc.match(/.+\.bmp$/)));
};
