/**
 * Displays a panel for converting the current user to an organization.
 */
angular.module('quay').directive('convertUserToOrg', function () {
  var directiveDefinitionObject = {
    priority: 0,
    templateUrl: '/static/directives/convert-user-to-org.html',
    replace: false,
    transclude: true,
    restrict: 'C',
    scope: {
      'user': '=user'
    },
    controller: function($scope, $element, Features, PlanService, Config, ApiService, CookieService, UserService) {
      $scope.convertStep = 0;
      $scope.org = {};
      $scope.loading = false;

      $scope.showConvertForm = function() {
        if (Features.BILLING) {
          PlanService.getMatchingBusinessPlan(function(plan) {
            $scope.org.plan = plan;
          });

          PlanService.getPlans(function(plans) {
            $scope.orgPlans = plans;
          });
        }

        $scope.convertStep = 1;
      };

      $scope.convertToOrg = function() {
        $('#reallyconvertModal').modal({});
      };

      $scope.reallyConvert = function() {
        if (Config.AUTHENTICATION_TYPE != 'Database') { return; }

        $scope.loading = true;

        var errorHandler = ApiService.errorDisplay(function() {
          $scope.loading = false;
        });

        var data = {
          'adminUser': $scope.org.adminUser,
          'adminPassword': $scope.org.adminPassword,
          'plan': $scope.org.plan ? $scope.org.plan.stripeId : ''
        };

        ApiService.convertUserToOrganization(data).then(function(resp) {
          CookieService.putPermanent('quay.namespace', $scope.user.username);
          UserService.load();
          $location.path('/');
        }, errorHandler);
      };
    }
  };
  return directiveDefinitionObject;
});