/* @ngInject */
module.exports = function ($scope, $urlRouter, $stateParams, $modal, AuthService, AUTH_EVENTS, $http) {
  $scope.currentUser = null;

  $scope.updateCurrentUser = function () {
    $scope.currentUser = AuthService.getCurrentUser();
    $scope.updateCurrentUserHeaders();
  };

  $scope.updateCurrentUserHeaders = function () {
    var token, email;
    if ($scope.currentUser) {
      token = $scope.currentUser.access_token;
      email = $scope.currentUser.email;
    }
    var defaultHeaders = {
      "Accept": "application/json",
      "X-User-Token": token,
      "X-User-Email": email,
    };
    $http.defaults.headers.common = defaultHeaders;
  };

  $scope.$on(AUTH_EVENTS.loginSuccess, function () {
    $scope.updateCurrentUser();
    if ($scope.currentUser.initialized === false) {
      $modal.open(
        require('init-person-modal')({
          person: $scope.currentUser,
        })
      ).result.then(function () {
        $urlRouter.sync();
      }, function (err) {
        // handle error
        $modal.open(
          require('error-modal')({ error: err })
        )
      });
    } else {
      $urlRouter.sync();
    }
  });

  $scope.$on(AUTH_EVENTS.logoutSuccess, function () {
    $scope.updateCurrentUser();
  });

  $scope.updateCurrentUser();
};

/* @ngInject */
module.exports = function ($scope, $urlRouter, $stateParams, $modal, AuthService, AUTH_EVENTS, $http) {
  $scope.currentUser = null;

  $scope.updateCurrentUser = function () {
    $scope.currentUser = AuthService.getCurrentUser();
    $scope.updateCurrentUserHeaders();
  };

  $scope.updateCurrentUserHeaders = function () {
    var token, email;
    if ($scope.currentUser) {
      token = $scope.currentUser.access_token;
      email = $scope.currentUser.email;
    }
    var defaultHeaders = {
      "Accept": "application/json",
      "X-User-Token": token,
      "X-User-Email": email,
    };
    $http.defaults.headers.common = defaultHeaders;
  };

  $scope.initializeUser = function () {
    $modal.open(
      require('init-person-modal')({
        person: $scope.currentUser,
      })
    ).result.then(function () {
      $urlRouter.sync();
    }, function (err) {
      // handle error
      if (err === "backdrop click") {
        $scope.initializeUser()
      } else if (err) {
        $modal.open(
          require('error-modal')({ error: err })
        )
      }
    });
  }

  $scope.$on(AUTH_EVENTS.loginSuccess, function () {
    $scope.updateCurrentUser();
    if ($scope.currentUser.initialized === false) {
      $scope.initializeUser()
    } else {
      $urlRouter.sync();
    }
  });

  $scope.$on(AUTH_EVENTS.logoutSuccess, function () {
    $scope.updateCurrentUser();
  });

  $scope.updateCurrentUser();
};

handle user initialization modal backdrop click