(function() {
  /**
   * Page that displays details about an user.
   */
  angular.module('quayPages').config(['pages', function(pages) {
    pages.create('user-view', 'user-view.html', UserViewCtrl, {
      'newLayout': true,
      'title': 'User {{ user.username }}',
      'description': 'User {{ user.username }}'
    })
  }]);

  function UserViewCtrl($scope, $routeParams, $timeout, ApiService, UserService, UIService, AvatarService, Config, ExternalLoginService) {
    var username = $routeParams.username;

    $scope.showAppsCounter = 0;
    $scope.showRobotsCounter = 0;
    $scope.showBillingCounter = 0;
    $scope.showLogsCounter = 0;

    $scope.changeEmailInfo = null;
    $scope.changePasswordInfo = null;
    $scope.hasSingleSignin = ExternalLoginService.hasSingleSignin();
    $scope.context = {};

    UserService.updateUserIn($scope);

    var loadRepositories = function() {
      var options = {
        'public': true,
        'namespace': username,
        'last_modified': true,
        'popularity': true
      };

      $scope.context.viewuser.repositories = ApiService.listReposAsResource().withOptions(options).get(function(resp) {
        return resp.repositories;
      });
    };

    var loadUser = function() {
      $scope.userResource = ApiService.getUserInformationAsResource({'username': username}).get(function(user) {
        $scope.context.viewuser = user;
        $scope.viewuser = user;

        $timeout(function() {
          // Load the repositories.
          loadRepositories();

          // Show the password change dialog if immediately after an account recovery.
          if ($routeParams.action == 'password' && UserService.isNamespaceAdmin(username)) {
            $scope.showChangePassword();
          }
        }, 10);
      });
    };

    // Load the user.
    loadUser();

    $scope.showRobots = function() {
      $scope.showRobotsCounter++;
    };

    $scope.showLogs = function() {
      $scope.showLogsCounter++;
    };

    $scope.showApplications = function() {
      $scope.showAppsCounter++;
    };

    $scope.showChangePassword = function() {
      $scope.changePasswordInfo = {};
    };

    $scope.changePassword = function(info, callback) {
      if (Config.AUTHENTICATION_TYPE != 'Database') { return; }

      var data = {
        'password': $scope.changePasswordInfo.password
      };

      var errorDisplay = ApiService.errorDisplay('Could not change password', callback);

      ApiService.changeUserDetails(data).then(function(resp) {
        // Reload the user.
        UserService.load();
        callback(true);
      }, errorDisplay);
    };

    $scope.generateClientToken = function() {
      var generateToken = function(password) {
        if (!password) {
          return;
        }

        var data = {
          'password': password
        };

        ApiService.generateUserClientKey(data).then(function(resp) {
          $scope.context.encryptedPasswordCredentials = {
            'username': UserService.getCLIUsername(),
            'password': resp['key'],
            'namespace': UserService.currentUser().username
          };
        }, ApiService.errorDisplay('Could not generate token'));
      };

      UIService.showPasswordDialog('Enter your password to generate an encrypted version:', generateToken);
    };

    $scope.showChangeEmail = function() {
      $scope.changeEmailInfo = {
        'email': $scope.context.viewuser.email
      };
    };

    $scope.changeEmail = function(info, callback) {
      var details = {
        'email': $scope.changeEmailInfo.email
      };

      var errorDisplay = ApiService.errorDisplay('Could not change email address', callback);

      ApiService.changeUserDetails(details).then(function() {
        $scope.context.emailAwaitingChange = $scope.changeEmailInfo.email;
        callback(true);
      }, errorDisplay);
    };

    $scope.showChangeAccount = function() {
      $scope.convertAccountInfo = {
        'user': $scope.context.viewuser
      };
    };

    $scope.showBilling = function() {
      $scope.showBillingCounter++;
    };
  }
})();