// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2008
// 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

const CC = Components.classes;
const CI = Components.interfaces;
const CR = Components.results;
const CU = Components.utils;

CU.import("resource:///modules/FlockXPCOMUtils.jsm");
FlockXPCOMUtils.debug = false;

CU.import("resource:///modules/FlockSvcUtils.jsm");
CU.import("resource:///modules/deliciousApi.jsm");
CU.import("resource:///modules/onlineFavoritesBackend.jsm");

const MODULE_NAME = "Delicious";

const CLASS_NAME = "Flock Delicious Service";
const CLASS_SHORT_NAME = "delicious";
const CLASS_TITLE = "del.icio.us";
const CLASS_ID = Components.ID("{5c54771f-2628-4200-af16-f94609177abd}");
const CONTRACT_ID = "@flock.com/delicious-service;1";

const SERVICE_ENABLED_PREF = "flock.service.delicious.enabled";

const DELICIOUS_URL = "http://del.icio.us";
const DELICIOUS_FAVICON = "http://del.icio.us/favicon.ico";
const DELICIOUS_API_URL = "https://api.del.icio.us/v1/";
const DELICIOUS_USER_URL_BASE = "http://del.icio.us";

const PREFERENCES_CONTRACTID = "@mozilla.org/preferences-service;1";
const PREFS = CC[PREFERENCES_CONTRACTID].getService(CI.nsIPrefBranch);

const DELICIOUS_STRING_BUNDLE = "chrome://flock/locale/services/delicious.properties";

// migration constants
const WEBSERVICE_PREF = "flock.favorites.webservice.id";
const OLD_DELICIOUS_PW_HOST = ":favorites:webservice:delicious:";

// One second, expressed in nsITimer terms.
const TIMER_SECOND = 1000;

/**************************************************************************
 * Component: Flock Delicious Service
 **************************************************************************/

// Constructor.
function flockDeliciousService() {
  this._init();

  FlockSvcUtils.flockIWebService.addDefaultMethod(this, "getAccount");
  FlockSvcUtils.flockIWebService.addDefaultMethod(this, "getAccounts");
  FlockSvcUtils.flockIWebService.addDefaultMethod(this, "logout");

  FlockSvcUtils.flockIManageableWebService
               .addDefaultMethod(this, "docRepresentsSuccessfulLogin");
  FlockSvcUtils.flockIManageableWebService
               .addDefaultMethod(this, "getAccountIDFromDocument");
  FlockSvcUtils.flockIManageableWebService
               .addDefaultMethod(this, "getCredentialsFromForm");
  FlockSvcUtils.flockIManageableWebService
               .addDefaultMethod(this, "ownsDocument");
  FlockSvcUtils.flockIManageableWebService
               .addDefaultMethod(this, "ownsLoginForm");
}


/**************************************************************************
 * Flock Delicious Service: XPCOM Component Creation
 **************************************************************************/

flockDeliciousService.prototype = new FlockXPCOMUtils.genericComponent(
  CLASS_NAME,
  CLASS_ID,
  CONTRACT_ID,
  flockDeliciousService,
  CI.nsIClassInfo.SINGLETON,
  [
    CI.nsIObserver,
    CI.nsITimerCallback,
    CI.flockIWebService,
    CI.flockIManageableWebService,
    CI.flockIBookmarkWebService,
    CI.flockIPollingService,
    CI.flockIMigratable
  ]
);

// FlockXPCOMUtils.genericModule() categories
flockDeliciousService.prototype._xpcom_categories = [
  { category: "wsm-startup" },
  { category: "flockMigratable" },
  { category: "flockWebService", entry: CLASS_SHORT_NAME }
];

/**************************************************************************
 * Flock Delicious Service: Private Data and Functions
 **************************************************************************/

// Member variables.
flockDeliciousService.prototype._init =
function DeliciousSvc__init() {
  FlockSvcUtils.getLogger(this).info(".init()");

  // Determine whether this service has been disabled, and unregister if so.
  prefService = CC["@mozilla.org/preferences-service;1"]
                .getService(CI.nsIPrefBranch);
  if (prefService.getPrefType(SERVICE_ENABLED_PREF) &&
     !prefService.getBoolPref(SERVICE_ENABLED_PREF))
  {
    this._logger.info("Pref " + SERVICE_ENABLED_PREF
                              + " set to FALSE... not initializing.");
    this.deleteCategories();
    return;
  }

  profiler = CC["@flock.com/profiler;1"].getService(CI.flockIProfiler);
  var evtID = profiler.profileEventStart("delicious-init");

  var obs = CC["@mozilla.org/observer-service;1"]
            .getService(CI.nsIObserverService);
  obs.addObserver(this, "xpcom-shutdown", false);

  this._api = new DeliciousAPI(DELICIOUS_API_URL, this._logger);
  this._accountClassCtor = flockDeliciousAccount;
  FlockSvcUtils.getACUtils(this);
  FlockSvcUtils.getCoop(this);
  if (this._coop.Service.exists(this.urn)) {
    this._c_svc = this._coop.get(this.urn);
  } else {
    this._c_svc = new this._coop.Service(this.urn, {
      name: CLASS_SHORT_NAME,
      desc: CLASS_TITLE
    });
  }
  this._c_svc.serviceId = CONTRACT_ID;
  this._c_svc.logoutOption = false;
  this._c_svc.domains = FlockSvcUtils.getWD(this)
                        .getString("delicious", "domains", "icio.us");

  profiler.profileEventEnd(evtID, "");
}

// Helper to retrieve tags on server.
flockDeliciousService.prototype._getAllTags =
function DeliciousSvc__getAllTags(aUrn, aAccountId,
                                  aPassword, aPollingListener) {
  this._logger.debug("getAllTags(...)");
  var svc = this;

  var flockListener = {
    onStart: function DeliciousSvc__getAllTags_onStart(aSubject, aTopic) {
      // Not used.
    },
    onSuccess: function DeliciousSvc__getAllTags_onSuccess(aSubject, aTopic) {
      svc._logger.info("tags/get SUCCEEDED: " + aTopic);

      var tags = [];
      for (var i = 0; i < aSubject.length; i++) {
        tags.push(aSubject[i].tag);
      }
      onlineFavoritesBackend.updateTags(svc, aAccountId, tags);

      // Tell the poller we're done
      if (aPollingListener) {
        aPollingListener.onResult();
      }
    },
    onError: function DeliciousSvc__getAllTags_onError(aSubject, aTopic, aError) {
      svc._logger.error("tags/get FAILED");
      // BUG: 5705 -  report error via notification bar?
      // onlineFavoritesBackend.showNotification(message);
      if (aPollingListener) {
        aPollingListener.onError(aError);
      }
    }
  }

  this._api.tagsGet(flockListener, null);
}

// Perform the version upgrade migration.
flockDeliciousService.prototype._migrateDeliciousAccount =
function DeliciousSvc_migrateDeliciousAccount(aContext) {
  var pm = CC["@mozilla.org/passwordmanager;1"]
           .getService(CI.nsIPasswordManager);
  var pw = this._acUtils.getFirstPasswordForHost(OLD_DELICIOUS_PW_HOST);

  // migrate online bm privacy settings
  PREFS.setBoolPref("flock.favorites.do." + CONTRACT_ID + "--" + pw.user, true);
  PREFS.setBoolPref("flock.favorites.private." + CONTRACT_ID + "--" + pw.user,
                    PREFS.getBoolPref("flock.favorites.privateByDefault"));

  var accountURN = this.urn + ":" + pw.user;
  pm.addUser(accountURN, pw.user, pw.password);
  pm.removeUser(OLD_DELICIOUS_PW_HOST, pw.user);
  var acct = this.addAccountById(pw.user, false, null);
  acct.activate(null);
  acct.keep(null);

  yield true;
}


/**************************************************************************
 * Flock Delicious Service: flockIWebService Implementation
 **************************************************************************/

// readonly attribute AString urn;
flockDeliciousService.prototype.urn = "urn:" + CLASS_SHORT_NAME + ":service";

// readonly attribute AString title;
flockDeliciousService.prototype.title = CLASS_TITLE;

// readonly attribute AString icon;
flockDeliciousService.prototype.icon = DELICIOUS_FAVICON;

// readonly attribute AString url;
flockDeliciousService.prototype.url = DELICIOUS_URL;

// readonly attribute AString contractId;
// ALMOST duplicated by nsIClassInfo::contractID
// with different case: contractId != contractID
// FIXME: File a bug for this as IDL is case-insensitive.
flockDeliciousService.prototype.contractId = CONTRACT_ID;

// readonly attribute AString shortName;
flockDeliciousService.prototype.shortName = CLASS_SHORT_NAME;

// readonly attribute boolean needPassword;
flockDeliciousService.prototype.needPassword = true;

// flockIWebServiceAccount addAccountById(in AString aAccountID,
//                                        in boolean aIsTransient,
//                                        in flockIListener aListener);
flockDeliciousService.prototype.addAccountById =
function DeliciousSvc_addAccountById(aAccountID, aIsTransient, aListener) {
  this._logger.debug("addAccountById('" + aAccountID + "', "
                     + aIsTransient + ", aListener)");
  var acct = onlineFavoritesBackend.createAccount(this,
                                                  aAccountID, aIsTransient);
  if (aListener) {
    aListener.onSuccess(acct, "addAccount");
  }
  return acct;
}

// void removeAccount(in AString aUrn);
flockDeliciousService.prototype.removeAccount =
function DeliciousSvc_removeAccount(aUrn) {
  this._logger.debug("removeAccount('" + aUrn + "')");
  onlineFavoritesBackend.removeAccount(this, aUrn);
}

// DEFAULT: flockIWebServiceAccount getAccount(in AString aUrn);
// DEFAULT: nsISimpleEnumerator getAccounts();
// DEFAULT: void logout();

// readonly attribute long status;
flockDeliciousService.prototype.status = CI.flockIWebService.STATUS_UNKNOWN;


/**************************************************************************
 * Flock Delicious Service: flockIManageableWebService Implementation
 **************************************************************************/

// DEFAULT: boolean docRepresentsSuccessfulLogin(in nsIDOMHTMLDocument aDocument);
// DEFAULT: AString getAccountIDFromDocument(in nsIDOMHTMLDocument aDocument);
// DEFAULT: nsIPassword getCredentialsFromForm(in nsIDOMHTMLFormElement aForm);
// DEFAULT: boolean ownsDocument(in nsIDOMHTMLDocument aDocument);
// DEFAULT: boolean ownsLoginForm(in nsIDOMHTMLFormElement aForm);

// void updateAccountStatusFromDocument(in nsIDOMHTMLDocument aDocument);
flockDeliciousService.prototype.updateAccountStatusFromDocument =
function DeliciousSvc_updateAccountStatusFromDocument(aDocument) {
  this._logger.debug("updateAccountStatusFromDocument()");

  if (this._WebDetective.detect("delicious", "loggedout", aDocument, null)) {
    this._acUtils.markAllAccountsAsLoggedOut(CONTRACT_ID);
  } else {
    if (this._WebDetective.detect("delicious", "loggedin", aDocument, null)) {
      var results = FlockSvcUtils.newResults();
      if (this._WebDetective.detect("delicious",
                                    "accountinfo", aDocument, results))
      {
        var accountID = results.getPropertyAsAString("accountid");
        var accountURN = this._acUtils.getAccountURNById(this.urn, accountID);
        this._acUtils.ensureOnlyAuthenticatedAccount(accountURN);
      }
    }
  }
}

/**************************************************************************
 * Flock Delicious Service: flockIBookmarkWebService Implementation
 **************************************************************************/

// void publish (in flockIListener aListener, in AString aAccountId,
//               in flockIBookmark aBookmark, in boolean aPrivate);
// flockIBookmarkWebService
flockDeliciousService.prototype.publish =
function DeliciousSvc_publish(aListener, aAccountId, aBookmark, aPrivate) {
  this._logger.info("Publish (" + aBookmark.URL + "," + aBookmark.name
                    + ") to " + aAccountId + "@Delicious");
  var accountUrn = this.urn + ":" + aAccountId;
  var password = this._acUtils.getPassword(accountUrn);
  var svc = this;
  var tags = aBookmark.tags;
  tags = tags ? tags.split(/[\s,]/).sort().join(" ").replace(/^ /, "") : "";
  var args = {
    url: aBookmark.URL,
    description: aBookmark.name,
    extended: aBookmark.description,
    tags: tags
  };
  if (aPrivate) {
    args.shared = "no";
  }

  var deliciousApiListener = {
    onError: function DeliciousSvc_publish_onError(aError) {
      svc._logger.error("posts/add FAILED");
      // BUG: 5705 -  report error via notification bar?
      // onlineFavoritesBackend.showNotification(message);
      if (aListener) {
        aListener.onError(svc, "publish", aError);
      }
    },
    onSuccess: function DeliciousSvc_publish_onSuccess(aXML) {
      svc._logger.info("posts/add SUCCEEDED");

      // Validate the nsIDOMDocument response.
      if (!svc._api.isExpectedResponse(aXML, "result")) {
        svc._logger.error("posts/add succeeded - but with invalid xml response");
        // BUG: 5705 -  report error via notification bar?
        // onlineFavoritesBackend.showNotification(message);
        if (aListener) {
          var error = CC["@flock.com/error;1"].createInstance(CI.flockIError);
          // FIXME: fill in this flockIError.
          error.errorCode = CI.flockIError.FAVS_UNKNOWN_ERROR;
          aListener.onError(svc, "publish", error);
        }
      } else {
        // Process the validated response.
        var result = aXML.documentElement.getAttribute("code");
        svc._logger.debug(" Result for posts/add: " + result);
        if (result == "done") {
          var localBookmarks = svc._coop.get(svc.urn + ":"
                                             + aAccountId + ":bookmarks");
          var tags = aBookmark.tags.split(" ");
          for (i in tags) {
            localBookmarks.tag.addOnce(tags[i]);
          }
          onlineFavoritesBackend.updateBookmark(svc, accountUrn,
                                                aBookmark, aPrivate);
          if (aListener) {
            aListener.onSuccess(svc, "publish");
          }
        } else if (aListener) {
          var error = CC["@flock.com/error;1"].createInstance(CI.flockIError);
          // FIXME: fill in this flockIError.
          error.errorCode = CI.flockIError.FAVS_UNKNOWN_ERROR;
          aListener.onError(svc, "publish", error);
        }
      }
    }
  }

  this._api.call("posts/add", args, deliciousApiListener, password);
}

// void publishList (in flockIListener aListener, in AString aAccountId,
//                   in nsISimpleEnumerator aBookmarkList, in boolean aPrivate);
flockDeliciousService.prototype.publishList =
function DeliciousSvc_publishList(aListener, aAccountId, aBookmarkList, aPrivate) {
  var delay = 1000; // 1 second between each query
  var svc = this;
  var i = 0;
  var bookmarks = [];

  var syncCallback = {
    notify: function publishListCallback_notify(timer) {
      var bm = bookmarks.shift();
      svc.publish(aListener, aAccountId, bm, aPrivate);
    }
  }

  while (aBookmarkList.hasMoreElements()) {
    var bookmark = aBookmarkList.getNext().QueryInterface(CI.flockIBookmark);
    // Duplicate it because it's going to be removed too early
    bookmarks[i] = {};
    bookmarks[i].URL = bookmark.URL;
    bookmarks[i].name = bookmark.name;
    bookmarks[i].description = bookmark.description;
    bookmarks[i].tags = bookmark.tags;
    bookmarks[i].time = bookmark.time;

    this._logger.debug("Set a timer to " + i * delay
                       + " for " + bookmarks[i].URL);
    var publishTimer = CC["@mozilla.org/timer;1"]
                       .createInstance(CI.nsITimer);
    publishTimer.initWithCallback(syncCallback, i * TIMER_SECOND,
                                  CI.nsITimer.TYPE_ONE_SHOT);
    i++;
  }
}

// void remove (in flockIListener aListener, in AString aAccountId,
//              in AString aBookmark);
flockDeliciousService.prototype.remove =
function DeliciousSvc_remove(aListener, aAccountId, aBookmark) {
  this._logger.info("Remove " + aBookmark + " from "
                    + aAccountId + "@Delicious");
  var password = this._acUtils.getPassword(this.urn + ":" + aAccountId);
  var svc = this;
  var args = { url: aBookmark };

  var deliciousApiListener = {
    onError: function DeliciousSvc_remove_onError(aError) {
      svc._logger.error("posts/delete FAILED");
      // BUG: 5705 -  report error via notification bar?
      // onlineFavoritesBackend.showNotification(message);
      if (aListener) {
        aListener.onError(svc, "remove", aError);
      }
    },
    onSuccess: function DeliciousSvc_remove_onSuccess(aXML) {
      svc._logger.info("posts/delete SUCCEEDED");

      // Validate the nsIDOMDocument response.
      if (!svc._api.isExpectedResponse(aXML, "result")) {
        svc._logger.error("posts/delete succeeded - but with invalid xml response");
        // BUG: 5705 -  report error via notification bar?
        // onlineFavoritesBackend.showNotification(message);
        if (aListener) {
          var error = CC["@flock.com/error;1"].createInstance(CI.flockIError);
          // FIXME: fill in this flockIError.
          error.errorCode = CI.flockIError.FAVS_UNKNOWN_ERROR;
          aListener.onError(svc, "remove", error);
        }
      } else {
        // Process the validated response.
        var result = aXML.documentElement.getAttribute("code");
        svc._logger.debug("Result for posts/delete: " + result);
        if (result == "done") {
          onlineFavoritesBackend.destroyBookmark(svc, aAccountId, aBookmark);
          CC["@flock.com/poller-service;1"].getService(CI.flockIPollerService)
          .forceRefresh(this.urn + ":" + aAccountId + ":bookmarks");
          if (aListener) {
            aListener.onSuccess(svc, "remove");
          }
        } else if (aListener) {
          var error = CC["@flock.com/error;1"].createInstance(CI.flockIError);
          // FIXME: fill in this flockIError.
          error.errorCode = CI.flockIError.FAVS_UNKNOWN_ERROR;
          aListener.onError(svc, "remove", error);
        }
      }
    }
  }

  this._api.call("posts/delete", args, deliciousApiListener, password);
}

// boolean exists (in AString aAccountId, in AString aURL);
flockDeliciousService.prototype.exists =
function DeliciousSvc_exists(aAccountId, aURL) {
  return this._coop.Bookmark.exists(this.urn + ":" + aAccountId + ":" + aURL);
}

// AString getUserURL (in AString aAccountId);
flockDeliciousService.prototype.getUserUrl =
function DeliciousSvc_getUserUrl(aAccountId) {
  return DELICIOUS_USER_URL_BASE + "/" + aAccountId;
}


/**************************************************************************
 * Flock Delicious Service: flockIPollingService Implementation
 **************************************************************************/

// void refresh(in AString aUrn, in flockIPollingListener aListener);
flockDeliciousService.prototype.refresh =
function DeliciousSvc_refresh(aURN, aPollingListener) {
  var svc = this;
  this._logger.info("refresh(" + aURN + ")");

  if (!this._coop.OnlineBookmarksStream.exists(aURN)) {
    throw "flockDeliciousService: " + aURN + " can't be found";
  }

  var bookmarks = this._coop.get(aURN);
  var accountId = bookmarks.userid;
  var accountUrn = this.urn + ":" + accountId;
  // nsIPassword for auth for this sync
  var password = this._acUtils.getPassword(accountUrn);

  var flockListener = {
    onStart: function DeliciousSvc_refresh_onStart(aSubject, aTopic) {
      // Not used.
    },
    onSuccess: function DeliciousSvc_refresh_onSuccess(aSubject, aTopic) {
      svc._logger.info("posts/all SUCCEEDED: " + aTopic);

      if (aTopic != "nonew") {
        onlineFavoritesBackend.updateLocal(svc, aSubject, aTopic, accountUrn);
        // Now refresh the tag list (wait one second)
        var syncCallback = {
          notify: function refreshCallback_notify(aTimer) {
            svc._getAllTags(aURN, accountId, password, aPollingListener);
          }
        }
        svc._logger.debug("Setting timer to execute _getAllTags()");
        svc._timer = CC["@mozilla.org/timer;1"].createInstance(CI.nsITimer);
        svc._timer.initWithCallback(syncCallback, TIMER_SECOND,
                                    CI.nsITimer.TYPE_ONE_SHOT);
        // For "updated" case, syncCallback calls onResult().
      } else if (aPollingListener) {
        aPollingListener.onResult();
      }
    },
    onError: function DeliciousSvc_refresh_onError(aSubject, aTopic, aError) {
      svc._logger.error("posts/all FAILED: ["
                        + aError.errorCode + "] "
                        + aError.errorString + " (["
                        + aError.serviceErrorCode + "] "
                        + aError.serviceErrorString + ")");

      var sbs = Cc["@mozilla.org/intl/stringbundle;1"]
                .getService(Ci.nsIStringBundleService);
      var bundle = sbs.createBundle(DELICIOUS_STRING_BUNDLE);

      var message;
      switch (aError.errorCode) {
        case CI.flockIError.FAVS_UNAVAILABLE:
          message = bundle.GetStringFromName("flock.delicious.error.unavailable");
          break;
        case CI.flockIError.FAVS_INVALID_AUTH:
          message = bundle.GetStringFromName("flock.delicious.error.invalid");
          break;
        default:
          message = bundle.formatStringFromName("flock.delicious.error",
                                                [aError.errorString,
                                                 aError.serviceErrorCode],
                                                2);
          break;
      }
      // need this delay for the migration case
      // see https://bugzilla.flock.com/show_bug.cgi?id=9051
      var syncCallback = {
        notify: function refreshCallback_notify(timer) {
          onlineFavoritesBackend.showNotification(message);
        }
      }
      svc._timer = CC["@mozilla.org/timer;1"].createInstance(CI.nsITimer);
      svc._timer.initWithCallback(syncCallback, TIMER_SECOND,
                                  CI.nsITimer.TYPE_ONE_SHOT);
      if (aPollingListener) {
        aPollingListener.onError(aError);
      }
    }
  }
  // even for the first refresh, we need to get the last update time from 
  // the server. Bruno
  this._api.postsUpdate(flockListener, password, bookmarks.last_update_time);
}

/**************************************************************************
 * Flock Delicious Service: nsIObserver Implementation
 **************************************************************************/

flockDeliciousService.prototype.observe =
function DeliciousSvc_observe(aSubject, aTopic, aState) {
  switch (aTopic) {
    case "xpcom-shutdown":
      var obs = CC["@mozilla.org/observer-service;1"]
                .getService(CI.nsIObserverService);
      obs.removeObserver(this, "xpcom-shutdown");
      break;
  }
}

/**************************************************************************
 * Flock Delicious Service: flockIMigratable Implementation
 * FIXME: Spinoff bug for cleanup of flockIMigrationManager.idl
 **************************************************************************/

flockDeliciousService.prototype.__defineGetter__("migrationName",
function DeliciousSvc_getter_migrationName() {
  return "Delicious Accounts";
});

// boolean needsMigration(in string oldVersion);
flockDeliciousService.prototype.needsMigration =
function DeliciousSvc_needsMigration(oldVersion) {
  // if online bookmarks webservice is configured AND using delicious
  var pw = this._acUtils.getFirstPasswordForHost(OLD_DELICIOUS_PW_HOST);
  if (PREFS.getPrefType(WEBSERVICE_PREF) &&
      PREFS.getCharPref(WEBSERVICE_PREF) == "delicious")
  {
    if (pw) {
      return true;
    } else {
      return false;
    }
  } else {
    // delicious is not configured so we might as well delete the pm entry
    // since account info is stored in rdf after migration
    if (pw) {
      var pm = CC["@mozilla.org/passwordmanager;1"]
               .getService(CI.nsIPasswordManager);
      pm.removeUser(OLD_DELICIOUS_PW_HOST, pw.user);
    }
    return false;
  }
}

// nsISupports startMigration(in string oldVersion,
//                            in flockIMigrationProgressListener aListener);
flockDeliciousService.prototype.startMigration =
function DeliciousSvc_startMigration(oldVersion,
                                     aFlockMigrationProgressListener) {
   var ctxt = {
     listener: aFlockMigrationProgressListener
   };

  return { wrappedJSObject: ctxt };
}

// boolean doMigrationWork(in nsISupports ctxt);
flockDeliciousService.prototype.doMigrationWork =
function DeliciousSvc_doMigrationWork(ctxt) {
  var context = ctxt.wrappedJSObject;

  if (!context.deliciousMigrator)
    context.deliciousMigrator = this._migrateDeliciousAccount(context);
  if (context.deliciousMigrator.next())
    context.deliciousMigrator = null;

  return Boolean(context.deliciousMigrator);
}

// void finishMigration(in nsISupports ctxt);
flockDeliciousService.prototype.finishMigration =
function DeliciousSvc_finishMigration(ctxt) {
}

/**************************************************************************
 * Component: Flock Delicious Account
 **************************************************************************/

function flockDeliciousAccount() {
  FlockSvcUtils.getLogger(this).info(".init()");
  FlockSvcUtils.getACUtils(this);
  FlockSvcUtils.getCoop(this);

  FlockSvcUtils.flockIWebServiceAccount.addDefaultMethod(this, "deactivate");
  FlockSvcUtils.flockIWebServiceAccount.addDefaultMethod(this, "login");
  FlockSvcUtils.flockIWebServiceAccount.addDefaultMethod(this, "logout");
  FlockSvcUtils.flockIWebServiceAccount.addDefaultMethod(this, "remove");
}

/**************************************************************************
 * Flock Delicious Account: XPCOM Component Creation
 **************************************************************************/

// Use genericComponent() for the goodness it provides (QI, nsIClassInfo, etc),
// but do NOT add flockDeliciousAccount to the list of constructors passed
// to FlockXPCOMUtils.genericModule().
flockDeliciousAccount.prototype = new FlockXPCOMUtils.genericComponent(
  CLASS_NAME + " Account",
  "",
  "",
  flockDeliciousAccount,
  0,
  [
    CI.flockIWebServiceAccount,
    CI.flockIBookmarkWebServiceAccount,
  ]
  );

/**************************************************************************
 * Flock Delicious Account: flockIWebServiceAccount Implementation
 **************************************************************************/

// readonly attribute AString urn;
flockDeliciousAccount.prototype.urn = "";

// void activate(in flockIListener aListener);
flockDeliciousAccount.prototype.activate =
function DeliciousAcct_activate(aListener) {
  this._logger.debug("activate()");
  this._coop.get(this.urn).isAuthenticated = true;
  this._coop.get(this.urn + ":bookmarks").isPollable = true;
  if (aListener) {
    aListener.onSuccess(this, "activate");
  }
}

// DEFAULT: void deactivate(in flockIListener aListener);
// DEFAULT: void login(in flockIListener aListener);
// DEFAULT: void logout(in flockIListener aListener);

// void keep();
flockDeliciousAccount.prototype.keep =
function DeliciousAcct_keep() {
  this._logger.debug("keep()");
  this._coop.get(this.urn).isTransient = false;
  this._coop.get(this.urn + ":bookmarks").isTransient = false;
  this._acUtils.makeTempPasswordPermanent(this.urn);
}

// DEFAULT: void remove();


/**************************************************************************
 * Flock Delicious Account: flockIBookmarkWebServiceAccount Implementation
 **************************************************************************/

/* No methods or properties on this interface! */


/**************************************************************************
 * XPCOM Support - Module Construction
 **************************************************************************/

// Create array of components.
var gComponentsArray = [flockDeliciousService];

// Generate a module for XPCOM to find.
var NSGetModule = FlockXPCOMUtils.generateNSGetModule(MODULE_NAME,
                                                      gComponentsArray);

/**************************************************************************
 * END XPCOM Support
 **************************************************************************/
