(function () {
    'use strict';

    angular
        .module('app')
        .controller('Login.IndexController', Controller)
        .factory('AlertService', function () {
          var success = {},
              error = {},
              alert = false;
          return {
            getSuccess: function () {
              return success;
            },
            setSuccess: function (value) {
              success = value;
              alert = true;
            },
            getError: function () {
              return error;
            },
            setError: function (value) {
              error = value;
              alert = true;
            },
            reset: function () {
              success = {};
              error = {};
              alert = false;
            },
            hasAlert: function () {
              return alert;
            }
          }
        });        

    function Controller($location, AuthenticationService, growl, AlertService) {
        var vm = this;

        vm.login = login;

        if (AlertService.hasAlert()) {
            growl.error(AlertService.getError());
            AlertService.reset();
        }
        
        initController();

        function initController() {
            // reset login status
            AuthenticationService.Logout();
        };

        function login() {
            vm.loading = true;
            AuthenticationService.Login(vm.username, vm.password, function (status, statusText) {
                if (status === 200) {
                    $location.path('/');
                } else {
                    growl.error('Login failed. (' + status + ' ' + statusText + ')');
                    vm.loading = false;
                }
            });
        };
    }

})();