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

Components.utils.import("resource:///modules/FlockCastUtils.jsm");

var UploadUIUtils = {};

UploadUIUtils.getCoop =
function UUIU_getCoop() {
  if (!this._coop) {
    this._coop = Cc["@flock.com/singleton;1"]
                 .getService(Ci.flockISingleton)
                 .getSingleton("chrome://flock/content/common/load-faves-coop.js")
                 .wrappedJSObject;
  }
  return this._coop;
};

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

UploadUIUtils.createMenuItem =
function UUIU_createMenuItem(aAttribs) {
  var menuitem = document.createElement("menuitem");
  for (var attrib in aAttribs) {
    menuitem.setAttribute(attrib, aAttribs[attrib]);
  }
  return menuitem;
};

UploadUIUtils.populateServicesPopup =
function UUIU_populateServicesPopup(aPopup) {
  var _coop = this.getCoop();

  // Clear out the current contents of the popup
  while (aPopup.firstChild) {
    aPopup.removeChild(aPopup.firstChild);
  }

  // Iterate through all accounts, looking for photo upload accounts.
  // Separate them according to auth state
  var loggedIn = [];
  var loggedOut = [];
  var accountsEnum = _coop.accounts_root.children.enumerate();
  while (accountsEnum.hasMoreElements()) {
    var acctCoopObj = accountsEnum.getNext();
    // getNext() can return NULL when hasMoreElements() is TRUE.
    if (!acctCoopObj || !Cc[acctCoopObj.serviceId]) continue;
    var svc = Cc[acctCoopObj.serviceId]
                        .getService(Ci.flockIWebService);
    if (svc instanceof Ci.flockIMediaUploadWebService) {
      this.getLogger().debug("found upload account on service: " + acctCoopObj.serviceId);
      var entry = {
        acct: acctCoopObj,
        svc: svc
      };
      if (acctCoopObj.isAuthenticated) {
        this.getLogger().debug(" - it's authenticated");
        loggedIn.push(entry);
      } else {
        this.getLogger().debug(" - it's NOT authenticated");
        loggedOut.push(entry);
      }
    }
  }

  // Grab a string bundle for the localized strings
  var stringBundle = FlockMedia.getStringBundle();

  // Add menu items for the authenticated accounts
  for (var i = 0; i < loggedIn.length; i++) {
    var acct = loggedIn[i].acct;
    var svc = loggedIn[i].svc;
    var acctName = svc.title + " (" + acct.name + ")";
    var itemLabel = stringBundle.GetStringFromName("flock.photo.service.use")
                                .replace("%account", acctName);
    var menuitem = UploadUIUtils.createMenuItem({
      value: acct.id(),
      src: acct.favicon,
      label: itemLabel
    });
    menuitem.svc = svc;
    aPopup.appendChild(menuitem);
  }

  if (loggedIn.length && loggedOut.length) {
    aPopup.appendChild(document.createElement("menuseparator"));
  }

  // Add menu items for the unauthenticated accounts
  for (var i = 0; i < loggedOut.length; i++) {
    var acct = loggedOut[i].acct;
    var svc = loggedOut[i].svc;
    var acctName = svc.title + " (" + acct.name + ")";
    var itemLabel = stringBundle.GetStringFromName("flock.photo.service.login")
                                .replace("%account", acctName);
    var menuitem = UploadUIUtils.createMenuItem({
      value: acct.id(),
      src: acct.favicon,
      label: itemLabel,
      oncommand: "UploadUIUtils.authAccount(this.value);"
    });
    menuitem.svc = svc;
    aPopup.appendChild(menuitem);
  }

  // Returns TRUE if there are authenticated accounts
  return (loggedIn.length > 0);
};

UploadUIUtils.authAccount =
function UUIU_authAccount(aAccountURN) {
  var acct = this.getCoop().get(aAccountURN);
  UploadUIUtils.authForService(acct.serviceId);
};

UploadUIUtils.authForService =
function UUIU_authForService(aServiceID) {
  var acUtils = Cc["@flock.com/account-utils;1"]
                          .getService(Ci.flockIAccountUtils);
  var svc = Cc[aServiceID]
                      .getService(Ci.flockILoginWebService)
                      .QueryInterface(Ci.flockIAuthenticateNewAccount);
  // We need to de-authenticate any currently authenticated account
  var accountUrn = svc.getAuthenticatedAccount();
  if (accountUrn) {
    svc.getAccount(accountUrn).logout(null);
  }
  svc.authenticateNewAccount();
};

UploadUIUtils.setDefaultAccount =
function UUIU_setDefaultAccount(aServiceList) {
  var defaultAccountId = FlockMedia.getUploadSvc().getDefaultService();
  var acUtils = Cc["@flock.com/account-utils;1"]
                .getService(Ci.flockIAccountUtils);

  // Handle the case where the upload service has a default account set.
  if (defaultAccountId) {
    var acct = this.getCoop().get(defaultAccountId);
    if (acct && acct.isAuthenticated) {
      aServiceList.value = defaultAccountId;
      return;
    }
  }

  // Get a list of the logged in accounts.
  var accounts = acUtils.getAccountsByInterface("flockIMediaUploadWebService");
  while (accounts.hasMoreElements()) {
    var account = accounts.getNext()
                          .QueryInterface(Ci.flockIWebServiceAccount);
    if (account.isAuthenticated()) {
      // If there is one or more logged in accounts pick the first one.
      aServiceList.selectedIndex = 0;
      return;
    }
  }
  aServiceList.selectedIndex = -1;
};

UploadUIUtils.launchUploadOptions =
function UUIU_launchUploadOptions(aParams) {
  var rv = window.openDialog("chrome://flock/content/photo/flockPhotoUploadOptions.xul",
                             "_blank", "modal,centerscreen", aParams);
  return rv;
};

UploadUIUtils.selectServiceGroupInSettings =
function UploadUIUtils_selectServiceGroupInSettings() {
  var sidebarObserver = Cc["@mozilla.org/observer-service;1"]
                        .getService(Ci.nsIObserverService);

  sidebarObserver.notifyObservers(sidebarObserver,
                                  "accountsSidebar",
                                  "Media Sharing");
};

UploadUIUtils.launchSettings =
function UUIU_launchSettings(aParams) {
  var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Ci.nsIWindowMediator);
  var win = wm.getMostRecentWindow('navigator:browser');
  var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"]
                                .getService(Ci.nsIPromptService);
  win.toggleSidebarWithMetric("flock_AccountsSidebarBroadcaster",
                              "AccountSidebar-Open",
                              null,
                              "PhotoUploaderNoAccounts",
                              true);
  // We need to delay so that the accounts and services sidebar
  // can open and load before we command it to do things.
  setTimeout("UploadUIUtils.selectServiceGroupInSettings();", 500);
};

UploadUIUtils.launchSinglePhotoUpload =
function UploadUIUtils_launchSinglePhotoUpload(aPhoto, aTarget) {
  var params = {
    aPhoto: aPhoto,
    aTarget: aTarget
  };
  var win = aTarget.ownerDocument.defaultView;
  win.openDialog("chrome://flock/content/photo/photoPropsQuickUpload.xul",
                 "QuickUploader", "modal,close,centerscreen", params);
};

UploadUIUtils.reportUploadToNewsFeed =
function pu_reportUploadToNewsFeed(aAccount, aPhotoArray) {
  var fbapi = Cc["@flock.com/api/facebook;1"].getService(Ci.flockIFacebookAPI);

  // Only report the public photos!
  // Not doing so would be a huge privacy invasion...
  var uploadedMedia = aPhotoArray;
  var publicMedia = [];
  for (i in uploadedMedia) {
    if (uploadedMedia[i] && uploadedMedia[i].is_public == "true") {
      publicMedia.push(uploadedMedia[i]);
    }
  }

  if (publicMedia.length == 0) {
    // It looks like everything was private
    return;
  }

  var photoEnum = {
    mData: publicMedia,
    hasMoreElements: function photoEnum_hasMoreElements() {
      return this.mData.length > 0;
    },
    getNext: function photoEnum_getNext() {
      return this.mData.shift();
    }
  }
  if (FlockCastUtils.isActive()) {
    fbapi.reportUpload(null, aAccount, photoEnum);
  }
}
