(function(){
    'use strict';

    angular.module('ammicoAuth',['ngRoute', 'ngMessages'])
    .controller('authCtrl', function($location, $rootScope, $routeParams, $modal){
        $modal.open({
            templateUrl: 'auth/' + $routeParams.action + '_modal.html',
            controller: 'auth' + $routeParams.action + 'Ctrl'
        }).result.then(function (result) {
            $location.path(result);
        }, function () {
            $location.path('/');
        });
    })
    .controller('authloginCtrl', function($modalInstance, $scope, authApi, $window, $http, $rootScope){
        $scope.login = function(){
            authApi.login.save({email:$scope.email, password:$scope.password}, function(data){
                $rootScope.globals.userLogged = true;
                localStorage.setItem('token', data.token);
                $http.defaults.headers.common.Authorization = 'Token ' + localStorage.getItem('token');
                $modalInstance.close('/');
            });
        };
        $scope.register = function () {
            $modalInstance.close('/auth/register');
        };
        $scope.cancel = function () {
            $modalInstance.close('/');
        };
    })
    .controller('authlogoutCtrl', function($modalInstance, $scope, $window, $http, $rootScope){
        localStorage.removeItem('token');
        $rootScope.globals.userLogged = false;
        delete $http.defaults.headers.common.Authorization;
        $scope.cancel = function () {
            $modalInstance.close('/');
        };
    })
    .controller('authregisterCtrl', function($scope, $modalInstance, authApi){
        $scope.message = '';

        $scope.user = {
            email: '',
            password: '',
            confirmPassword: ''
        };

        $scope.submit = function(isValid) {
            console.log(isValid);
            console.log($scope);
            console.log($scope.email);
            if (isValid) {
                authApi.user.save({
                    email: $scope.user.email,
                    password: $scope.user.password,
                }, function(){
                    $modalInstance.close('/auth/login');
                });
            } else {
                $scope.message = 'Il reste toujours des champs invalides';
            }
        };
        $scope.back = function () {
            $modalInstance.close('/auth/login');
        };
    })
    .directive('compareTo', function(){
        return {
            require: 'ngModel',
            scope: {
                otherModelValue: '=compareTo'
            },
            link: function($scope, element, attributes, ngModel) {

                ngModel.$validators.compareTo = function(modelValue) {
                    return modelValue === $scope.otherModelValue;
                };

                $scope.$watch('otherModelValue', function() {
                    ngModel.$validate();
                });
            }
        };
    });
})();
