const UserLogin = function ($scope, PubSub, $location, AuthService) {
  $scope.credentials = {
    email: undefined,
    password: undefined
  }

  $scope.submit = () => {
    AuthService.login($scope.credentials)
            .then(user => {
              if (user) {
                $location.path('/a/orders')
              }
              else {
                throw new Error('Authentication failed')
              }
            })
            .catch(err => {
              PubSub.publish('alert', { msg: err.data ? err.data.message : err.message, type: 'danger' })
            })
  }

  AuthService.getUser().then(user => {
    if (user) {
      $location.path('/a/orders')
    }
  })
}

UserLogin.$inject = ['$scope', 'PubSub', '$location', 'AuthService']

export default UserLogin
