angular.module('avalanche3mobile.LoginCtrl', ['avalancheServices.Oauth'])

  .controller('LoginCtrl', ['$scope', '$rootScope', '$location', '$ionicModal', '$timeout', '$ionicSideMenuDelegate', '$cordovaStatusbar', 'OAuthService', '$state', function($scope, $rootScope, $location, $ionicModal, $timeout, $ionicSideMenuDelegate, $cordovaStatusbar, OAuthService, $state) {

    // Initialize variables
    $scope.login = { email : "", password: ""};

    $ionicModal.fromTemplateUrl('templates/modals/login.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.openLogin = function() {
      $scope.modal.show();
    };
    $scope.closeLogin = function() {
      $scope.modal.hide();
    };
    //Cleanup the modal when we're done with it!
    $scope.$on('$destroy', function() {
      $scope.modal.remove();
    });
    // Execute action on hide modal
    $scope.$on('modal.hidden', function() {
      // Execute action
    });
    // Execute action on remove modal
    $scope.$on('modal.removed', function() {
      // Execute action
    });

    $scope.authorizeUser = function(){
      console.log("Authorizing user...");
      OAuthService.authorizeUser($scope.login.email, $scope.login.password);
    }

    $rootScope.$on('auth:success', function() {
      if(!$scope.$$phase) {
        $scope.$apply(function(){
          $scope.redirectLoggedInUser();
        });
      } else {
        $scope.redirectLoggedInUser();
      }
    });

    $scope.redirectLoggedInUser = function() {
      $scope.modal.hide();
      var missions = OAuthService.getMissions();
      if(missions.length > 0) {
        $state.go("mission.briefing", { missionId: missions[0].slug});
      } else {
        $state.go("app.search");
      }
    }

  }]);
