var userControllers = angular.module('mindinkControllers');

angular.module('passwordValidation', []).directive('validPasswordC', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue, $scope) {
                if (scope.registerForm) {
                    var noMatch = viewValue != scope.registerForm.password.$viewValue;
                    scope.passwordNoMatch = noMatch;
                    ctrl.$setValidity('noMatch', !noMatch);
                }
                else if (scope.resetPasswordForm){
                    var noMatch = viewValue != scope.resetPasswordForm.password.$viewValue;
                    ctrl.$setValidity('noMatch', !noMatch);
                    scope.invalid = noMatch;
                }
            })
        }
    }
});

userControllers.controller('userCtrl',[ '$scope', '$modal', '$cookieStore', '$location', '$rootScope', 'userFactory',
    function($scope, $modal, $cookieStore, $location, $rootScope, userFactory) {

        $scope.showTermsAlert = false;
        $scope.attemptedRegister = false;

        $scope.register = function(method){

            if (!!$scope.agree){
                $scope.showTermsAlert = false;
                switch(method){
                    case "email": $location.path("/register"); break;
                    case "facebook": break;
                    case "twitter": break;
                };
            }else {
                $scope.showTermsAlert = true;
            }

        };

        $scope.registerEmailUser = function() {
            $scope.attemptedRegister = true;
            $scope.inProgress = true;

            if ($scope.passwordNoMatch != undefined && !$scope.passwordNoMatch && $scope.firstName !== undefined && $scope.lastName !== undefined && $scope.email !== undefined && $scope.password !== undefined) {
                userFactory.emailSignUp($scope.firstName, $scope.lastName, $scope.email, $scope.password);
            }
            else {
                $scope.passwordNoMatch = ($scope.passwordNoMatch == undefined)? true : $scope.passwordNoMatch;

                // if the password do match, reset the invalid;
                $scope.invalid = ($scope.password != undefined && !$scope.passwordNoMatch);
                $scope.inProgress = false;
            }
        };

        $scope.activateUser = function() {
            if ($location.$$search.g != undefined){
                userFactory.activateUser($location.$$search.g);
            }
        };

        $scope.attemptedSignIn = false;
        $scope.emailSignin = function() {
            $scope.attemptedSignIn = true;
            $scope.inProgress = true;

            if ($scope.email != undefined &&  $scope.password != undefined) {
                $scope.rememberMe = ($scope.rememberMe)?$scope.rememberMe:false;

                $scope.invalid = false;
                userFactory.emailSignin($scope.email, $scope.password, $scope.rememberMe);
            }
        };

        $scope.termsOpen = function() {
            $modal.open({
                templateUrl: 'html/terms.html',
                controller: signUpPopupCtrl
            });
        };

        $scope.privacyOpen = function() {
            $modal.open({
                templateUrl: 'html/privacy.html',
                controller: signUpPopupCtrl
            });
        };

        $scope.signout = function() {
            userFactory.emailSignout();
        };

        $scope.requestNewPassword = function() {
            $scope.inProgress = true;

            if ($scope.email != undefined){
                $scope.invalid = false;
                userFactory.requestNewPassword($scope.email);
            }
            else {
                // show error message
            }
        };

        $scope.resetPassword = function() {
            $scope.attemptResetPassword = true;
            $scope.inProgress = true;

            if ($location.$$search.u != undefined && $scope.password != undefined){
                userFactory.resetPassword($location.$$search.u, $scope.password);
            }
            else {
                // show error message
            }
        };

        $rootScope.$on("email_signup_success", function (event, args) {
            $scope.inProgress = false;
            $rootScope.userId = args.userId;
            $location.path('/mindink');
        });

        $rootScope.$on("email_signup_fail", function (event, args) {
            $scope.invalid = true;
            $scope.inProgress = false;
            if (args.status == "EMAIL_TAKEN"){
                $scope.message = "* Sorry, that email address is already in use.";
            }
            else if (args.status == "INVALID_EMAIL_FORMAT"){
                $scope.message = "* Sorry, your email format appears to be invalid.";
            }
            else {
                $scope.message = "* There is an error on the request. Please try again later.";
            }
        });

        $rootScope.$on("email_signin_success", function (event, args) {
            $rootScope.userId = args.userId;
            $scope.inProgress = false;
            $location.path('/mindink');
        });

        $rootScope.$on("email_signin_fail", function (event, args) {
            $scope.invalid = true;
            $scope.inProgress = false;

            $scope.message = "* Login failed.";
        });

        $rootScope.$on("activate_user_success", function (event, args) {
//            alert("activated");
        });

        $rootScope.$on("activate_user_fail", function (event, args) {
//            alert("not activated");
        });

        $rootScope.$on("email_signout_success", function (event, args) {
            $location.path('/index');
        });

        $rootScope.$on("email_signout_fail", function (event, args) {

        });

        $rootScope.$on("request_new_password_success", function (event, args) {
            $scope.inProgress = false;
            $location.path('/forgotpasswordsent');
        });

        $rootScope.$on("request_new_password_fail", function (event, args) {
            $scope.invalid = true;
            $scope.inProgress = false;

            if (args.status == "USER_NOT_EXIST"){
                $location.path('/forgotpasswordsent');
//                $scope.message = "* Email cannot be found.";
            }
            else if (args.status == "REQUEST_PASSWORD_FAIL"){
                $scope.message = "* There is error on the request. Please try again later.";
            }
            else {
                $scope.message = "* There is error on the request. Please try again later.";
            }
        });

        $rootScope.$on("reset_password_success", function (event, args) {
            $scope.inProgress = false;
//            $scope.successMessage = "* Your password has been set. Please sign in with your password.";
            $location.url('/mindink');
        });

        $rootScope.$on("reset_password_fail", function (event, args) {
            $scope.invalid = true;
            $scope.inProgress = false;

            $scope.message = "* There is error on the request. Please try again later."
        });
    }]);


userControllers.directive('ngLoginSubmit', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var inputs = element.find("input");
            var len = inputs.length;

            $timeout(function(){
                for (var i=0; i < len; i++){
                    if (inputs[i].id == "email") {
                        scope.email = inputs[i].value;
                    }
                    else if (inputs[i].id == "password"){
                        scope.password = inputs[i].value;
                    }
                }
            }, 100);
        }
    };
}]);

userControllers.controller('readerCtrl', ['$scope', function($scope) {
    EPUBJS.filePath = "js/epub/libs/";
    //var book = ePub("book/A-Life-That-Counts.epub");
    var book = ePub("book/moby-dick.epub");

    book.renderTo("eReader");

    $scope.prevPage = function() {
        book.prevPage();
    }
    $scope.nextPage = function() {
        book.nextPage();
    }
}]);

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
var signUpPopupCtrl = function ($scope, $modalInstance) {
    $scope.ok = function () {
        $modalInstance.dismiss('cancel');
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
};