//
// 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 gPhoto;
var gSelectedApi;
var gPhotoMgrSvc;
var gPrefSvc;
var gTarget;
var gApiListener;
var gLogger;

var gAccountObserver = {
  onAccountAuthenticated: function acctObs_onAccountAuthenticated(aAccount) {
    gLogger.debug("accountObserver: onAccountAuthenticated('"
                  + aAccount.urn + "')");
    var api = aAccount.getService();

    // Only detect auth changes for uploadable accounts
    if (api instanceof Ci.flockIMediaUploadWebService) {
      var servicesMenuList = $("servicesMenuList");
      var selectedAccountUrn = servicesMenuList.value;
      UploadUIUtils.populateServicesPopup(servicesMenuList.firstChild);
      // Reselect the previously selected account
      servicesMenuList.value = selectedAccountUrn;
      serviceChanged();
    }
  },
  onAccountUnauthenticated: function acctObs_onAccountUnauthenticated(aAccount)
  {
    gLogger.debug("accountObserver: onAccountUnauthenticated('"
                  + aAccountUrn + "')");
    var api = aAccount.getService();

    // Only detect auth changes for uploadable accounts
    if (api instanceof Ci.flockIMediaUploadWebService) {
      var servicesMenuList = $("servicesMenuList");
      var selectedAccountUrn = servicesMenuList.value;
      UploadUIUtils.populateServicesPopup(servicesMenuList.firstChild);
      if (selectedAccountUrn == aAccount.urn) {
        // Select blank item
        servicesMenuList.selectedIndex = -1;
      } else {
        // Reselect the previously selected account
        servicesMenuList.value = selectedAccountUrn;
      }
      serviceChanged();
    }
  },
  onAccountRefreshing: function acctObs_onAccountRefreshing(aAccount) {
    gLogger.debug("accountObserver: onAccountRefreshing('"
                  + aAccount.urn + "')");
  },
  onAccountNoLongerRefreshing:
  function acctObs_onAccountNoLongerRefreshing(aAccount) {
    gLogger.debug("accountObserver: onAccountNoLongerRefreshing('"
                  + aAccount.urn + "')");
  }
};

// Set the state of the upload button.
function checkUploadButton() {
  DEBUG("checkUploadButton()");
  if (isReadyForUpload()) {
    $("cmd_doUpload").removeAttribute("disabled");
  } else {
    $("cmd_doUpload").setAttribute("disabled", "true");
  }
}

// Determine whether we are ready to upload photo(s).
function isReadyForUpload() {
  DEBUG("isReadyForUpload()");
  var serviceList = $("servicesMenuList");
  if (serviceList.selectedIndex > -1) {
    var accountURN = serviceList.value;
    DEBUG("accountURN = " + accountURN);
    if (accountURN) {
      var account = serviceList.selectedItem.svc.getAccount(accountURN);
      // Selected account is authenticated so we are ready to upload.
      if (account.isAuthenticated()) {
        return true;
      }
    }
  }

  return false;
}

// Handle changes to the service selection.
function serviceChanged() {
  var serviceList = $("servicesMenuList");
  if (serviceList.selectedIndex == -1) {
    photoProperties.setupUIFields();
  } else {
    photoProperties.setupUIFields(serviceList.value);
  }
  checkUploadButton();
}

function init() {
  gLogger = Components.classes["@flock.com/logger;1"]
            .createInstance(Components.interfaces.flockILogger);
  gLogger.init("singlePhotoUpload");
  // need to wrap in an array :/
  gPhotoMgrSvc = Components.classes['@flock.com/photo-api-manager;1?'].getService(Components.interfaces.flockIPhotoAPIManager);
  gPrefSvc = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);

  $('batch-radio').collapsed = true;

  var serviceList = $("servicesMenuList");
  UploadUIUtils.populateServicesPopup(serviceList.firstChild);
  UploadUIUtils.setDefaultAccount(serviceList);

  var uploadItems = Array();
  gPhoto = window.arguments[0].aPhoto;
  uploadItems.push(gPhoto);
  gTarget = window.arguments[0].aTarget;
  photoProperties.setUploadType(UPLOAD_TYPE_DND);
  photoProperties.setSelection(uploadItems);
  serviceChanged();

  var accountService = Components.classes["@flock.com/account-service;1"]
                       .getService(Components.interfaces.flockIAccountService);
  accountService.addObserver(gAccountObserver);
}

function unload() {
  var accountService = Components.classes["@flock.com/account-service;1"]
                       .getService(Components.interfaces.flockIAccountService);
  accountService.removeObserver(gAccountObserver);
}

function flock_updateSelectedAPI() {
  var selectedApi = $("flockPhotoservicesList").value;
  if (selectedApi) {
    gSelectedApi = gPhotoMgrSvc.getAPIFromShortname($("flockPhotoservicesList").value);
    $('bcasterServiceUploadSelected').removeAttribute('disabled');
    flock_updatePhotoOptionFields();
  } else {
    $('bcasterServiceUploadSelected').setAttribute('disabled', true);
  }
}

function flock_updatePhotoOptionFields() {
  flock_setupPhotoPropsUIFields(gSelectedApi);
}

function flock_launchSingleUpload() {
  // var service = gPhotoMgrSvc.getDefaultService();
  var service = $('servicesMenuList').selectedItem.svc;
  gSelectedApi = service;

  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());

  if (!service.getAuthenticatedAccount()) {
    var loginListener = {
      onSuccess: function(aSubject, aTopic) {
        if (service.getAuthenticatedAccount()) {
          flock_launchUploadOptions();
        }
      },
      onError: function(aError) { }
    };

    var accountURN = $("servicesMenuList").value;
    var account = service.getAccount(accountURN);
    account.login(loginListener);
  } else {
    flock_launchUploadOptions();
  }
}

function flock_launchUploadOptions() {
//  var params = {};
  var photoUploads = Array();

  photoUploads.push(window.arguments[0].aPhoto);
//  params.photoUploads = photoUploads;
//  params.aPhoto = window.arguments[0].aPhoto;
//  params.aTarget = gTarget;
//  params.numUploads = 1;

  var params = {
    service: $('servicesMenuList').selectedItem.svc,
    accountURN: $('servicesMenuList').selectedItem.value,
    photoUploads: photoUploads
  };
  DEBUG("doUpload(): Get the photos");

  var rv = window.openDialog("chrome://flock/content/photo/flockPhotoUploadOptions.xul",
                             "_blank", "modal,centerscreen", params);
  if (rv && params.launchUploader == true) {
    gPhoto.album = params.albumId;
    photoProperties.synch();
    flock_doSingleUpload();
    return true;
  } else {
    return false;
  }
}

function flock_doSingleUpload() {
  var rval = {};
  var api = gSelectedApi;
  window.openDialog("chrome://flock/content/photo/uploadingSinglePhoto.xul",
                    "UploadingSinglePhoto", "modal, centerscreen", api, gPhoto,
                    rval);
  var photo = rval.photo;
  var html = photo.buildHTML();

  var account = api.getAccount($('servicesMenuList').selectedItem.value);
  UploadUIUtils.reportUploadToNewsFeed(account, [photo]);

  // TODO - the html should be inserted where the mouse cursor was when the drop occurred 
  // not just at the end

  if (gTarget.tagName == "editor") {
    gTarget.contentWindow.document.body.innerHTML = gTarget.contentWindow.document.body.innerHTML + html;
  }
  else {
    gTarget.value = gTarget.value + html;
  }
  window.close();
  window.blur();
  return;
}
