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

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

const MODULE_NAME = "AuthManager";
const CLASS_NAME = "Flock Authentication Manager";
const CLASS_SHORT_NAME = "authmgr";
const CLASS_TITLE = "Auth Manager";
const CLASS_ID = Components.ID("{96b62c22-4420-4b64-b919-3bf62af335b1}");
const CONTRACT_ID = "@flock.com/authmgr;1";

// Associative array of "network" => array("service contract IDs")
var gNetworks = [];


function AuthManager() {
  FlockSvcUtils.getLogger(this);
  this._logger.init(CLASS_SHORT_NAME);
  FlockSvcUtils.getCoop(this);
  FlockSvcUtils.getACUtils(this);
}

AuthManager.prototype = new FlockXPCOMUtils.genericComponent(
  CLASS_NAME,
  CLASS_ID,
  CONTRACT_ID,
  AuthManager,
  CI.nsIClassInfo.SINGLETON,
  [
    CI.flockIAuthenticationManager
  ]
);


// BEGIN flockIAuthenticationManager
AuthManager.prototype.joinNetwork =
function AuthManager_joinNetwork(aServiceID, aNetworkName)
{
  this._logger.info(".joinNetwork('" + aServiceID + "', '"
                                     + aNetworkName + "')");
  if (!gNetworks[aNetworkName]) {
    gNetworks[aNetworkName] = [];
  }
  gNetworks[aNetworkName].push(aServiceID);
}

AuthManager.prototype.findPasswordFromRelatedAccount =
function AuthManager_findPasswordFromRelatedAccount(aServiceID, aAccountId)
{
  this._logger.info(".findPasswordFromRelatedAccount('" + aServiceID + "', '"
                                                        + aAccountId + "')");
  function flockILoginInfo(aUser, aPassword) {
    return {
      QueryInterface: function authmgr_flockILoginInfo_QI(aIID) {
        if (!aIID.equals(CI.nsISupports) &&
            !aIID.equals(CI.nsILoginInfo) &&
            !aIID.equals(CI.flockILoginInfo))
        {
          throw CR.NS_ERROR_NO_INTERFACE;
        }
        return this;
      },
      formSubmitURL: "",
      httpRealm: "",
      hostname: "",
      username: aUser,
      usernameField: "",
      password: aPassword,
      passwordField: "",
      formType: "authMgr"
    };
  }
  // Loop through all services in the network
  var network = this._getNetworkForService(aServiceID);
  for each (var contractID in gNetworks[network]) {
    if (contractID && CC[contractID]) {
      var svc = CC[contractID].getService(CI.flockIWebService);
      var accountUrns = svc.getAccountUrns();
      // Loop through all the accounts urns configured for this service
      while (accountUrns && accountUrns.hasMore()) {
        var c_acct = this._coop.Account.get(accountUrns.getNext());
        if (c_acct) {
          var accountId = c_acct.accountId;
          var pwKey = svc.urn + ":" + accountId;
          var pw = this._acUtils.getPassword(pwKey);
          if (pw) {
            // We have a password for this account, let's see if it matches
            // aAccountId
            if (accountId.toLowerCase() == aAccountId.toLowerCase() ||
                pw.username.toLowerCase() == aAccountId.toLowerCase())
            {
              return flockILoginInfo(pw.username, pw.password);
            }
          }
        }
      }
    } else {
      this._logger.warn("no service for contractID: " + contractID);
    }
  }
  return null;
}

AuthManager.prototype.reportAccountAuthState =
function AuthManager_reportAccountAuthState(aAccount, aIsLoggedIn)
{
  this._logger.info(".reportAccountAuthState('" + aAccount.urn + "', "
                                                + aIsLoggedIn + ")");
  if (aIsLoggedIn) {
    // The initial account whose auth state is changing is considered a
    // "catalyst" account.  The "catalyst" account has just been logged in to.
    // This implies that:
    //   (1) Accounts using *different* account IDs are now logged OUT; and
    //   (2) Accounts using the same ID on other services are now also
    //       logged IN.
    var catalystServiceId = aAccount.getService().contractId;
    var network = this._getNetworkForService(catalystServiceId);
    if (!network) {
      this._logger.error("ERROR: network is null!!");
      return;
    }
    for each (var contractID in gNetworks[network]) {
      if (contractID == catalystServiceId) {
        // We don't need to update any accounts from the catalyst service; it's
        // assumed that they are already accounted for.
        continue;
      }
      if (contractID && CC[contractID]) {
        var svc = CC[contractID].getService(CI.flockIWebService);
        var accountUrns = svc.getAccountUrns();
        while (accountUrns && accountUrns.hasMore()) {
          var account = svc.getAccount(accountUrns.getNext())
                           .QueryInterface(CI.flockIWebServiceAccount);
          var isAuthenticated = account.isAuthenticated();
          if (isAuthenticated && !this._areAccountsRelated(account, aAccount))
          {
            if (isAuthenticated) {
              this._logoutAccount(account);
            }
          }
        }
      } else {
        this._logger.warn("no service for contractID: " + contractID);
      }
    }
  } else {
    // aAccountURN has just been logged out of.  This does not necessarily imply
    // that any other accounts are automatically logged in or out.
  }
}

AuthManager.prototype.reportCompleteLoginToNetwork =
function AuthManager_reportCompleteLoginToNetwork(aAccount)
{
  this._logger.info(".reportCompleteLoginToNetwork('" + aAccount.urn + "')");
  var catalystServiceId = aAccount.getService().contractId;
  var network = this._getNetworkForService(catalystServiceId);
  if (!network) {
    this._logger.error("ERROR: network is null!!");
    return;
  }
  for each (var contractID in gNetworks[network]) {
    if (contractID && CC[contractID]) {
      var svc = CC[contractID].getService(CI.flockIWebService);
      var accountUrns = svc.getAccountUrns();
      while (accountUrns && accountUrns.hasMore()) {
        var account = svc.getAccount(accountUrns.getNext())
                         .QueryInterface(CI.flockIWebServiceAccount);
        if (this._areAccountsRelated(account, aAccount)) {
          if (contractID != catalystServiceId && !account.isAuthenticated())
          {
            // This is an account with the same ID, in the same network, but for
            // a different service.  We need to make sure it's logged in.
            this._loginAccount(account);
          }
        } else {
          // This is an account in the same network, but with a different ID.
          // We need to ensure that it's logged out.
          if (account.isAuthenticated()) {
            this._logoutAccount(account);
          }
        }
      }
    } else {
      this._logger.warn("no service for contractID: " + contractID);
    }
  }
}

AuthManager.prototype.reportCompleteLogoutFromNetwork =
function AuthManager_reportCompleteLogoutFromNetwork(aServiceID)
{
  this._logger.info(".reportCompleteLogoutFromNetwork('" + aServiceID + "')");
  var network = this._getNetworkForService(aServiceID);
  if (!network) {
    this._logger.error("ERROR: network is null!!");
    return;
  }
  for each (var contractID in gNetworks[network]) {
    if (contractID && CC[contractID]) {
      var svc = CC[contractID].getService(CI.flockIWebService);
      var accountUrns = svc.getAccountUrns();
      while (accountUrns && accountUrns.hasMore()) {
        var account = svc.getAccount(accountUrns.getNext())
                         .QueryInterface(CI.flockIWebServiceAccount);
        if (account.isAuthenticated()) {
          this._logoutAccount(account);
        }
      }
    } else {
      this._logger.warn("no service for contractID: " + contractID);
    }
  }
}
// END flockIAuthenticationManager


// Returns TRUE iff the two accounts are related in their network.
// Assumes that they belong to the same network.
AuthManager.prototype._areAccountsRelated =
function AuthManager__areAccountsRelated(aAcct1, aAcct2)
{
  var account1Id = aAcct1.getParam("accountId");
  var account2Id = aAcct2.getParam("accountId");
  if (account1Id == account2Id) {
    return true;
  }
  var pwKey1 = aAcct1.getService().urn + ":" + account1Id;
  var pw1 = this._acUtils.getPassword(pwKey1);
  if (pw1 && pw1.username && pw1.username == account2Id) {
    return true;
  }
  var pwKey2 = aAcct2.getService().urn + ":" + account2Id;
  var pw2 = this._acUtils.getPassword(pwKey2);
  if (pw2 && pw2.username && pw2.username == account1Id) {
    return true;
  }
  if (pw1 && pw1.username && pw1.username.length &&
      pw2 && pw2.username && pw2.username.length &&
      pw1.username == pw2.username)
  {
    return true;
  }
  return false;
}

AuthManager.prototype._getNetworkForService =
function AuthManager__getNetworkForService(aContractID)
{
  for (var network in gNetworks) {
    var services = gNetworks[network];
    for each (var cid in services) {
      if (cid == aContractID) {
        this._logger.debug("network is: " + network);
        return network;
      }
    }
  }
  return null;
}

AuthManager.prototype._loginAccount =
function AuthManager__loginAccount(aAccount)
{
  this._logger.debug("._loginAccount('" + aAccount.urn + "')");
  var inst = this;
  var loginListener = {
    onSuccess: function loginListener_onSuccess(aSubject, aTopic) {
      inst._logger.debug("loginListener.onSuccess() " + aAccount.urn);
    },
    onError: function loginListener_onError(aFlockError, aTopic) {
      inst._logger.error("loginListener.onError() " + aAccount.urn);
    }
  };
  aAccount.login(loginListener);
}

AuthManager.prototype._logoutAccount =
function AuthManager__logoutAccount(aAccount)
{
  this._logger.debug("._logoutAccount('" + aAccount.urn + "')");
  var inst = this;
  var logoutListener = {
    onSuccess: function logoutListener_onSuccess(aSubject, aTopic) {
      inst._logger.debug("logoutListener.onSuccess() " + aAccount.urn);
    },
    onError: function logoutListener_onError(aFlockError, aTopic) {
      inst._logger.error("logoutListener.onError() " + aAccount.urn);
    }
  };
  aAccount.logout(logoutListener);
}


// Create array of components.
var componentsArray = [AuthManager];

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