/**
 * Service which monitors the current user session and provides methods for returning information
 * about the user.
 */
angular.module('quay')
       .factory('UserService', ['ApiService', 'CookieService', '$rootScope', 'Config',

function(ApiService, CookieService, $rootScope, Config) {
  var userResponse = {
    verified: false,
    anonymous: true,
    username: null,
    email: null,
    organizations: [],
    logins: [],
    beforeload: true
  }

  var userService = {}

  userService.hasEverLoggedIn = function() {
    return CookieService.get('quay.loggedin') == 'true';
  };

  userService.updateUserIn = function(scope, opt_callback) {
    scope.$watch(function () { return userService.currentUser(); }, function (currentUser) {
      scope.user = currentUser;
      if (opt_callback) {
        opt_callback(currentUser);
      }
    }, true);
  };

  userService.load = function(opt_callback) {
    var handleUserResponse = function(loadedUser) {
      userResponse = loadedUser;

      if (!userResponse.anonymous) {
        if (Config.MIXPANEL_KEY) {
          mixpanel.identify(userResponse.username);
          mixpanel.people.set({
            '$email': userResponse.email,
            '$username': userResponse.username,
            'verified': userResponse.verified
          });
          mixpanel.people.set_once({
            '$created': new Date()
          })
        }

        if (window.olark !== undefined) {
          olark('api.visitor.getDetails', function(details) {
            if (details.fullName === null) {
              olark('api.visitor.updateFullName', {fullName: userResponse.username});
            }
          });
          olark('api.visitor.updateEmailAddress', {emailAddress: userResponse.email});
          olark('api.chat.updateVisitorStatus', {snippet: 'username: ' + userResponse.username});
        }

        if (window.Raven !== undefined) {
          Raven.setUser({
            email: userResponse.email,
            id: userResponse.username
          });
        }

        CookieService.putPermanent('quay.loggedin', 'true');
      } else {
        if (window.Raven !== undefined) {
          Raven.setUser();
        }
      }

      if (opt_callback) {
        opt_callback();
      }
    };

    ApiService.getLoggedInUser().then(function(loadedUser) {
      handleUserResponse(loadedUser);
    }, function() {
      handleUserResponse({'anonymous': true});
    });
  };

  userService.isOrganization = function(name) {
    return !!userService.getOrganization(name);
  };

  userService.getOrganization = function(name) {
    if (!userResponse || !userResponse.organizations) { return null; }
    for (var i = 0; i < userResponse.organizations.length; ++i) {
      var org = userResponse.organizations[i];
      if (org.name == name) {
        return org;
      }
    }

    return null;
  };

  userService.isNamespaceAdmin = function(namespace) {
    if (namespace == userResponse.username) {
      return true;
    }

    var org = userService.getOrganization(namespace);
    if (!org) {
      return false;
    }

    return org.is_org_admin;
  };

  userService.isKnownNamespace = function(namespace) {
    if (namespace == userResponse.username) {
      return true;
    }

    var org = userService.getOrganization(namespace);
    return !!org;
  };

  userService.currentUser = function() {
    return userResponse;
  };

  // Update the user in the root scope.
  userService.updateUserIn($rootScope);

  // Load the user the first time.
  userService.load();

  return userService;
}]);
