// 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/FlockPrefsUtils.jsm");
Components.utils.import("resource:///modules/FlockCastUtils.jsm");

const FLOCK_PREF_PHOTO_RESIZE = "flock.photo.resize";
const FLOCK_PREF_PHOTO_RESIZE_DIMENSIONS = "flock.photo.resize.dimensions";

// function DEBUG(x) { dump("photoUploadOptions.js: "+x+"\n"); }
function DEBUG(x) {}

var gPhotoUploadSvc = null;
var gSelectedAPI = null;
var gAccount = null;
var gPhotoUploads = null;

var gFbApi = Components.classes["@flock.com/api/facebook;1"]
             .getService(Components.interfaces.flockIFacebookAPI);

function $(aId) {
  return document.getElementById(aId);
}

/*var gAPIListener = {
  onAPIStateChange: function(aAPI) {
    if (aAPI.getAuthenticatedAccount()) {
      gSelectedAPI = aAPI;
      setupAuthenticatedService();
    }
    //setupServicesMenu();
  },
  onError: function(aFlockError) {
  }
}*/

const ACCOUNT_USAGE_WARNING_THRESHOLD = 0.7;

function unload() {
}

function initUploadOptions() {
  DEBUG("initUploadOptions()");
  var params  = window.arguments[0];

  gPhotoUploadSvc = Components.classes["@flock.com/media/upload-service;1"]
                              .getService(Components.interfaces.flockIPhotoUploadService)
  // gPhotoMgrSvc = Components.classes['@flock.com/photo-api-manager;1?']
  //  .getService(Components.interfaces.flockIPhotoAPIManager);

  flock_photoPrefLoad();

  //gSelectedAPI =  gPhotoMgrSvc.getDefaultService();
  DEBUG("initUploadOptions(): with serviceId = "+params.service.contractId);
  gSelectedAPI = params.service;

  // Make sure there's a selected item in the Quality menulist
  if (!$("flockPhotoQualityList").selectedItem) {
    $("flockPhotoQualityList").selectedIndex = 0;
  }

  // Show FlockCast controls unless we are using Facebook
  if (FlockCastUtils.isActive() && gSelectedAPI.shortName != "facebook") {
    $("flockcast-upload-box").removeAttribute("hidden");
    // If there is no logged in Facebook account disable FlockCast
    // checkbox and show explanation text
    if (!FlockCastUtils.hasLoggedInFlockCastAccount()) {
      $("flockcast-upload-checkbox").setAttribute("disabled", "true");
      $("flockcast-upload-login-text").removeAttribute("hidden");
    }
  }

  if (!gSelectedAPI) {
    UploadUIUtils.launchSettings();
  } else {
    gAccount = gSelectedAPI.getAccount(params.accountURN);
    setupAuthenticatedService();
  }

  updatePhotoSizeUI($("flockPhotoResizeRadioGroup"));
  document.documentElement.getButton("accept").focus();
}

function updatePhotoSizeUI(aTarget) {
	if (aTarget.localName == 'radiogroup') {
		$('flockPhotoQualityList').disabled = (aTarget.selectedItem.id == 'flock-photo-neverResize');	
	}
}

function setupAuthenticatedService() {
  setupAlbumList();

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

  var nfCheckbox = $("flockcast-upload-checkbox");
  if (!nfCheckbox.hasAttribute("disabled")) {
    nfCheckbox.setAttribute("checked",
                            FlockCastUtils.getPublishAction(gAccount, "upload"));
  }
  $('uploadSettingsTitle').setAttribute('value', stringBundle.GetStringFromName("flock.photo.upload.settings.for").replace(/%service/g, gSelectedAPI.title));
  gPhotoUploads = window.arguments[0].photoUploads;
  $('flock-upload-num-photos').setAttribute('value', gPhotoUploads.length);
  flock_SetEstimatedSize();
}

function flock_SetEstimatedSize() {
  var dims = parseInt($('flockPhotoQualityList').selectedItem.value);
  $("flock-upload-estimated-size").setAttribute("value", flock_getBatchUploadSize(dims) + " MB");
}

function flock_getResizedDims(aDims, aTargetSize) {
  return (aTargetSize * aDims.y) / aDims.x;
}

function getFileFromPath(aPath) {
  var file = Components.classes["@mozilla.org/file/local;1"]
                       .createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(aPath);
  return file;
}

function flock_getBatchUploadSize(aResizeDim) {
  var resizeSize = aResizeDim;
  var previewFile;
  var batchUploadFileSize = 0;
  var previewPixelRatio = 0;
  var largestSide = 0;
  var previewDims = 0;
  var originalDims;
  var estimatedSize;
  for (var i = 0; i < gPhotoUploads.length; i++) {
    if ($('flockPhotoResizeRadioGroup').selectedItem.id == 'flock-photo-alwaysResize') {
      // this is the fast test
      var originalDims = {};
      originalDims.x = aResizeDim;
      originalDims.y = aResizeDim;
      previewPixelRatio = .19;  // this is the param to tweak
      estimatedSize = resizeSize * resizeSize * previewPixelRatio;
      batchUploadFileSize = batchUploadFileSize + estimatedSize;
    } else {
      batchUploadFileSize = batchUploadFileSize
                          + getFileFromPath(gPhotoUploads[i].originalFilePath)
                            .fileSize;
    }
  }
  return (batchUploadFileSize/(1024*1024)).toFixed(2);
}

function flock_photoPrefSetResize(aObj) {
  if (aObj.selectedItem.id == 'flock-photo-alwaysResize') {
    $("flockPhotoQualityList").removeAttribute("disabled");
    FlockPrefsUtils.setBoolPref(FLOCK_PREF_PHOTO_RESIZE, true)
  } else {
    $("flockPhotoQualityList").setAttribute("disabled",  true);
    FlockPrefsUtils.setBoolPref(FLOCK_PREF_PHOTO_RESIZE, false);
  }
}

function flock_disableAlbumSelection(aShouldDisable) {
  if (aShouldDisable) {
    $('flock-photo-albums').setAttribute('disabled', true);
    $('flock-createAlbumBtn').setAttribute('disabled', true);
  } else {
    $('flock-photo-albums').removeAttribute('disabled');
    $('flock-createAlbumBtn').setAttribute('disabled', !gSelectedAPI.supportsFeature('albumCreation'));
  }
}

function flock_photoPrefSetQuality(aValue) {
  FlockPrefsUtils.setIntPref(FLOCK_PREF_PHOTO_RESIZE_DIMENSIONS, aValue);
}

function flock_photoUploadAccept() {
  flock_savePhotoUploadPrefs();
  window.arguments[0].launchUploader = true;
  window.arguments[0].apiName=gSelectedAPI.shortName;
  window.arguments[0].resize = $("flockPhotoQualityList").value;
  window.arguments[0].newAlbum = false;
  if (!$('flock-photo-skipalbum').selected) {
    window.arguments[0].albumId = $("flock-photo-albums").value;
    var selectedAlbum = $("flock-photo-albums").selectedItem;
    if (selectedAlbum) {
      window.arguments[0].albumTitle = selectedAlbum.label;
      if (selectedAlbum.getAttribute("newAlbum")) {
        window.arguments[0].newAlbum = true;
      }
    }
  }
  else {
    window.arguments[0].albumId = "";
  }
  return window.arguments[0];
}

function flock_photoUploadCancel() {
  window.arguments[0].launchUploader = false;
}

function flock_savePhotoUploadPrefs() {
  FlockPrefsUtils.setIntPref(FLOCK_PREF_PHOTO_RESIZE_DIMENSIONS,
                             $("flockPhotoQualityList").selectedItem.value);
  FlockPrefsUtils.setBoolPref(FLOCK_PREF_PHOTO_RESIZE,
                              $("flockPhotoResizeRadioGroup").value == "true");
  FlockPrefsUtils.setBoolPref("flock.photo.uploader.upload2Album",
                              $("flock-photo-addtoalbum").selected);
}

function flock_photoPrefLoad() {
  var resize = FlockPrefsUtils.getBoolPref(FLOCK_PREF_PHOTO_RESIZE);
  if (resize == "" || resize == null) {
    FlockPrefsUtils.setBoolPref(FLOCK_PREF_PHOTO_RESIZE, false);
    resize = FlockPrefsUtils.getBoolPref(FLOCK_PREF_PHOTO_RESIZE);
  }
  $("flockPhotoResizeRadioGroup").value = resize;
  var maxDim = FlockPrefsUtils.getIntPref(FLOCK_PREF_PHOTO_RESIZE_DIMENSIONS);
  $("flockPhotoQualityList").value = maxDim;
  //flock_photoPrefSetConfigEnabled();
  var upload2Album = FlockPrefsUtils.getBoolPref('flock.photo.uploader.upload2Album');
  if (upload2Album) {
    $("flock-photo-skipalbum").removeAttribute("selected");
    $("flock-photo-addtoalbum").setAttribute("selected", "true");
  } else {
    $("flock-photo-skipalbum").setAttribute("selected", "true");
    $("flock-photo-addtoalbum").removeAttribute("selected");
    flock_disableAlbumSelection(true);
  }
}

function setupAlbumList() {
  var acceptBtn = document.documentElement.getButton("accept");
  acceptBtn.setAttribute("disabled", true);
  while ($("flock-photo-albums-popup").childNodes.length > 1) {
    $("flock-photo-albums-popup").removeChild($("flock-photo-albums-popup").lastChild);
  }

  $("loading-albums").setAttribute("collapsed", false);
  $("flock-photo-albums").selectedIndex = 0;
  $("flock-photo-albums").setAttribute("disabled", true);

  if (gSelectedAPI.shortName) {
    var AlbumListener = function() {};
    AlbumListener.prototype = {
      onSuccess: function setupAlbumList_al_onSuccess(aSubject, aTopic) {
        while ($("flock-photo-albums-popup").childNodes.length > 1) {
          $("flock-photo-albums-popup").removeChild($("flock-photo-albums-popup").lastChild);
        }
        if ($('flock-photo-addtoalbum').selected) {
          $("flock-photo-albums").removeAttribute("disabled");
        }
        $("loading-albums").setAttribute("collapsed", true);
        aSubject.QueryInterface(Components.interfaces.nsISimpleEnumerator);
        while (aSubject.hasMoreElements()) {
          var album = aSubject.getNext();
          album.QueryInterface(Components.interfaces.flockIPhotoAlbum);
          var menuitem = document.createElement("menuitem");
          $("flock-photo-albums-popup").appendChild(menuitem);
          menuitem.setAttribute("label", album.title);
          menuitem.setAttribute("tooltiptext", album.title);
          menuitem.setAttribute("value", album.id);
        }
        // select the first non-none album
        $("flock-photo-albums").selectedIndex = 1;
        if (gSelectedAPI.supportsFeature('albumCreation')) {
          $('flock-createAlbumBtn').removeAttribute('disabled')
        }
        gSelectedAPI.getAccountStatus(this.accountStatusListener);
      },
      
      accountStatusListener : {
        onSuccess: function(aResult, aTopic) {
          acceptBtn.removeAttribute("disabled");
          aResult.QueryInterface(Components.interfaces.nsIPropertyBag2);
          $("upload-usage-deck").selectedIndex = 0;
          const ONE_MILLION = 1000000;
          var maxSpace = aResult.getPropertyAsAString("maxSpace");
          var usedSpace = aResult.getPropertyAsAString("usedSpace");
          var usageUnits = aResult.getPropertyAsAString("usageUnits");
          var isPremium = aResult.getPropertyAsBool("isPremium");
          var usage = (usedSpace / maxSpace);

          switch (usageUnits) {
            case "bytes":
              maxSpace = Math.round(maxSpace / ONE_MILLION);
              usedSpace = Math.round(usedSpace / ONE_MILLION);
              break;
            case "Megabytes":
              break;
          }

          var usageString = usedSpace + '/' + maxSpace + ' MB';

          $('flock-upload-account-usage').setAttribute('value', (usage*100)+'%');
          $('flock-upload-account-usage-nums').setAttribute('value', usageString);
          $('flock-current-usage').removeAttribute('collapsed');
          // special case for photobucket -- this will disappear when album creation is supported
          if (gSelectedAPI.shortName != "photobucket") {
            $('flock-createAlbumBtn').removeAttribute('disabled');
          }

          var showUpgradeWarning = usage > ACCOUNT_USAGE_WARNING_THRESHOLD;
          if (!isPremium && showUpgradeWarning) {
            var strBundle = document.getElementById('stringBundle');
            var msg = strBundle.getString('flock.photo.upload.outofspace');
            $('flock-photo-upgradeAccountInfo').removeAttribute('hidden');
            var upgradeString = msg.replace('%1', gSelectedAPI.serviceName);
            $('flock-photo-upgradeAccountInfoMessage').firstChild.nodeValue = upgradeString;
          }

          // special case for Flickr since they allow 3 sets for free accounts
          if (gSelectedAPI.shortName == "flickr"
              && !isPremium
              && $("flock-photo-albums-popup").childNodes.length > 3)
          {
            $('flock-createAlbumBtn').setAttribute('disabled', true);
            if (!showUpgradeWarning) {
              var strBundle = document.getElementById('stringBundle');
              var msg = strBundle.getString('flock.photo.upload.setlimit');
              var upgradeString = msg.replace('%1', 3).replace('%2', gSelectedAPI.serviceName);
            }

          }
          window.sizeToContent();
        },
        
        onError: function(aError) {
          $("upload-usage-deck").selectedIndex = 1;
        }
      },
      
      onError: function setupAlbumList_al_onError(aFlockError, aTopic) {
        var strBundle = document.getElementById('stringBundle');
        alert(strBundle.getString('flock.photo.upload.error.2'));
      }
    }

    if (gAccount) {
      var flockListener = new AlbumListener();
      var accountId = gAccount.getParam("accountId");
      gSelectedAPI.getAlbumsForUpload(flockListener, accountId);
    }
  }
}

function openCreateAlbumDlg() {
  var strBundle = document.getElementById('stringBundle');
  var windowTitle = strBundle.getString("flock.photo.upload.create.title");
  var text = strBundle.getString("flock.photo.upload.create.text");
  var rval;
  var popup = $("flock-photo-albums-popup");
  for (;;) {
    rval = prompt(strBundle.getString("flock.photo.upload.create.name"), text, windowTitle, null, null);
    if (rval == null) return;
    var noMatch = true;
    for (var i = 0; i < popup.childNodes.length; ++i) {
      var child = popup.childNodes.item(i);
      if (child.label == rval) {
        noMatch = false;
        break;
      }
    }
    if (noMatch) break;
    alert(strBundle.getString("flock.photo.upload.create.exists"));
  }
  if (rval && rval!=text) {
    var optionsDialog = $("photoUploaderOptions");
    var acceptBtn = optionsDialog.getButton("accept");

    //create the album
    var albumListener = {
      onSuccess: function openCrAlbDlg_al_onSuccess(aSubject, aTopic) {
        var menuitem = document.createElement("menuitem");
        var secondItem = $("flock-photo-albums-popup").firstChild.nextSibling;
        if (secondItem == null) {
          $("flock-photo-albums-popup").appendChild(menuitem);
        }
        else {
          $("flock-photo-albums-popup").insertBefore(menuitem, secondItem);
        }
        aSubject.QueryInterface(Components.interfaces.flockIPhotoAlbum);
        menuitem.setAttribute("label", aSubject.title);
        menuitem.setAttribute("value", aSubject.id);
        menuitem.setAttribute("tooltiptext", aSubject.title);
        menuitem.setAttribute("newAlbum", true);
        // Select the first non-NONE album.
        $("flock-photo-albums").selectedIndex = 1;
        acceptBtn.removeAttribute("disabled");
      },
      onError: function openCrAlbDlg_al_onError(aFlockError, aTopic) {
        acceptBtn.removeAttribute("disabled");
      }
    }

    acceptBtn.setAttribute("disabled", true);
    var accountId = gAccount.getParam("accountId");
    gSelectedAPI.createAlbum(albumListener, accountId, rval);
  }
}

function onUploadWhatsThisClick() {
  var flockcast = document.getElementById("flockcast-upload-box");
  if (!flockcast.hasAttribute("expanded")) {
    flockcast.setAttribute("expanded", "true");
    window.sizeToContent();

    var metrics = Components.classes["@flock.com/metrics-service;1"]
                  .getService(Components.interfaces.flockIMetricsService);
    metrics.report("FlockCast-Whats-This-Clicked", "upload");
  }
}
