var LogInView = Backbone.View.extend({
    breadcrumb: {},

    events: {
        'click .save-button' : 'logIn',
        'keyup #password' : 'checkForEnter',
        'click #newPasswordUpdate' : 'changePassword',
        'click #continueWithoutUpdate' : 'continueWithWeakPassword',
        'click #confirmContinueWithoutUpdateYes' : 'confirmContinueWithoutUpdate',
        'click #confirmContinueWithoutUpdateNo' : 'closeLastChanceWarningModal',
        'click #resetPassword' : 'openResetPasswordModal',
        'click #sendResetEmail' : 'sendResetEmail',
        'click #validatePasscode' : 'validatePasscode',
        'click #updatePassword' : 'updatePassword',
    },

    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.breadcrumb = options.breadcrumb;
        this.israCardBuild = options.israCardBuild;
        this.model = options.model;
    },

    render: function () { 
        var that = this;
        // document.cookie = "sessionCookie" + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        // this.slideOut = $('.sidenav').hide();
        // this.navWrapper = $('.nav-wrapper').hide();
        // this.white = $('.white').hide();

        this.$el.html(this.template({
            logIn: this.model.toJSON(),
        }));
        
        App.setBreadcrumbs(this.breadcrumb);

        $(document).on('keydown', 'input, select', function(e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
              ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select,button,select').filter(':visible');
                next = focusable.eq(focusable.index(this)+1);
                if (next.length) {
                    next.focus();
                } else {
                    form.submit();
                }
                return false;
            }
        });

        $(document).ready(function () {
            document.getElementById('password').focus();
            if (that.israCardBuild) {
                $('.apLogInLogo').hide();
                $('.israCardLogInLogo').show();
            }
            else {
                $('.apLogInLogo').show();
                $('.israCardLogInLogo').hide();
            }
        });

        return this;
    },

    checkForEnter: function (e) {
        if (e.keyCode == 13) {
            this.$el.find(".save-button").trigger("click");
        }
    },

    continueWithWeakPassword: function() {
        if(this.strongPswdCount > 1)
            this.logIn(null, true);
        else if( this.strongPswdCount == 1)
            this.$el.find('#last-chance-warning-modal').modal().modal('open');

    },

    closeLastChanceWarningModal() {
        this.$el.find('#last-chance-warning-modal').modal().modal('close');
    },

    confirmContinueWithoutUpdate: function() {
        this.logIn(null, true);
    },

    logIn: function (e, continueWithWeakPassword = false) {
        var that = this;

        var password = this.$el.find('#password').val();
        // App.password = password;
        var rkEncryptionKey = CryptoJS.enc.Base64.parse('u/Gu5posvwDsXUnV5Zaq4g==');
        var rkEncryptionIv = CryptoJS.enc.Base64.parse('5D9r9ZVzEYYgha93/aUK2w==');
        var utf8Stringified = CryptoJS.enc.Utf8.parse(password);
        var encrypted = CryptoJS.AES.encrypt(password, rkEncryptionKey, {mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: rkEncryptionIv});
        var ciphertext = encrypted.ciphertext.toString(CryptoJS.enc.Base64);

        var newPassword = document.getElementById('newPassword').value;
        var newPasswordCipherText = '';
        if(newPassword != '' && !continueWithWeakPassword) {   
            var encryptedNewPassword = CryptoJS.AES.encrypt(newPassword, rkEncryptionKey, {mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: rkEncryptionIv});
            var newPasswordCipherText = encryptedNewPassword.ciphertext.toString(CryptoJS.enc.Base64);
        }

        document.querySelector('.progress').style.visibility = 'visible';
        var loginBtn = document.querySelector('#logInButtons a');
        loginBtn.classList.add('disabled');

        $.ajax({
            url: '/data/log-in',
            data: {
                password: ciphertext,
                newPassword: newPasswordCipherText,
                continueWithWeakPassword: continueWithWeakPassword
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                loginBtn.classList.remove('disabled');
                document.querySelector('.progress').style.visibility = 'hidden';
                that.strongPswdCount = data.strongPswdCount;
                var weakPassword = data.weakPassword;
              
                if(weakPassword && !continueWithWeakPassword && that.strongPswdCount > 0) {
                    that.openNewPasswordModal(that.strongPswdCount);
                }
                else {
                    that.model.set(data);
                    that.setToken();
                    App.initialize();
                }

                if(continueWithWeakPassword)
                    M.toast({ html: that.strongPswdCount +'{Literal} Logins left with old password!{/Literal}', displayLength: 10000 });
            },

            error: function (e) {
                loginBtn.classList.remove('disabled');
                document.querySelector('.progress').style.visibility = 'hidden';
                if (e.status == 520) {
                    M.toast({ html: '{Literal}Server Not Fully Loaded. Please wait a few seconds and try again.{/Literal}' });
                }
                else if (e.status == 521) {
                    M.toast({ html: '{Literal}Invalid User Login{/Literal}' });
                }
                else if (e.status == 522) {
                    M.toast({ html: '{Literal}No Access to Web Management{/Literal}' });
                }
            }
        });
    },

    setToken: function () {
        if (this.model.attributes.token.length > 0) {
            this.setCookie("sessionCookie", this.model.attributes.token);
            var expireDate = (new Date()).getTime();
            expireDate += 1000 * SESSION_TIMEOUT;
            this.setCookie("expiration-date", expireDate);
            window.location.href = "#/home";
            // this.navWrapper.show();
            // this.white.show();  
            // this.slideOut.show();
        }
        else {
            M.toast({ html: '{Literal}Invalid User Login{/Literal}' });
        }
    },
    
    setCookie: function (name, value) {
        document.cookie = name + "=" + (value || "");
    },

    openNewPasswordModal: function(strongPswdCount, ) {
        var newPasswordModal = this.$el.find('#new-password-form-modal').modal();

        if(strongPswdCount > 0) {
            document.getElementById('continueWithoutUpdate').removeAttribute('disabled','disabled');
            document.getElementById('confirmPassword').parentElement.style.display = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('newPassword').type = 'password';
            document.getElementById('confirmPassword').value = '';
            document.getElementById('new-password-message').innerText = strongPswdCount +'{Literal} Logins left with old password!{/Literal}';
        } else {
            document.getElementById('continueWithoutUpdate').setAttribute('disabled','disabled');
            document.getElementById('new-password-message').innerText = "{Literal}No logins left with old password, you must change the password in order to login.{/Literal}";
            var autoGeneratedPassword = this.generatePassword();
            document.getElementById('newPassword').value = autoGeneratedPassword;
            document.getElementById('newPassword').type = 'text';
            document.getElementById('confirmPassword').parentElement.style.display = 'none';
            document.getElementById('confirmPassword').value = autoGeneratedPassword;
        }

        newPasswordModal.modal('open');
    },

    generatePassword: function() {
        var chars = "0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var passwordLength = 8;
        var password = "";

        for (var i = 0; i <= passwordLength; i++) {
            var randomNumber = Math.floor(Math.random() * chars.length);
            password += chars.substring(randomNumber, randomNumber +1);
        }

        return password;
     },

    changePassword: function () {
        var validateConfirmPassword = !document.getElementById('confirmPassword').style.display == 'none';
        var valid = this.newPasswordValidation(validateConfirmPassword);
        if(valid)
            this.logIn();
    },

    newPasswordValidation: function (validateConfirmPassword) {
        var iChars = "`~!@#$%^&*()_+=[]{}:,<>./*\\\'\"";
        var currentPassword = document.getElementById("password").value;
        var newPasswordEl = document.getElementById("newPassword");
        var newPassword = newPasswordEl.value;
        var newPasswordHelperTextEl = document.querySelector("#newPassword ~ .helper-text");
        var helperTextNew = '';

        var confirmPasswordEl = document.getElementById("confirmPassword");
        var confirmPassword = confirmPasswordEl.value;
        var confirmPasswordHelperTextEl = document.querySelector("#confirmPassword ~ .helper-text");
        var helperTextConfirm = '';

        if(newPassword.length < 8 || newPassword.length > 20)
            helperTextNew = '{Literal}Password must be at least 8 characters long{/Literal}';
        else if(!newPassword.match(/^(?=.*[A-Z])/))
            helperTextNew = '{Literal}Password must include one uppercase letter{/Literal}';
        else if(!newPassword.match(/^(?=.*[a-z])/))
            helperTextNew = '{Literal}Password must include one lowercase letter{/Literal}';
        else if(!newPassword.match(/^(?=.*\d)/))
            helperTextNew = '{Literal}Password must include one number{/Literal}';
        else if(!newPassword.match(/[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/))
            helperTextNew = '{Literal}Password must include one special character{/Literal}';
        else if(newPassword == currentPassword)
            helperTextNew = '{Literal}New password must be different from the current password{/Literal}';

        var valid = true;
        newPasswordHelperTextEl.innerText = helperTextNew;
        newPasswordEl.classList = '';
        if(helperTextNew == '') {
            newPasswordEl.classList.add('valid');
            if(newPassword != confirmPassword && validateConfirmPassword) {
                helperTextConfirm = '{Literal}Confirm password doesn\'t match{/Literal}';
                confirmPasswordHelperTextEl.innerText = helperTextConfirm;
                confirmPasswordEl.classList.add('invalid');
                valid = false;
            }
        }
        else {
            newPasswordEl.classList.add('invalid');
            valid = false;
        }

        return valid;
    },

    // reset password section

    openResetPasswordModal: function() {
        var modal = this.$el.find('#reset-password-modal').modal();
        document.getElementById("resetPart1").style.display = 'block';
        document.getElementById("resetPart2").style.display = 'none';
        document.getElementById("resetPart3").style.display = 'none';
        document.getElementById('passcode').value = '';
        document.getElementById("newResetPassword").value = '';
        document.getElementById("confirmResetPassword").value = '';

        modal.modal('open');
    },

    sendResetEmail(){
        $.ajax({
            url: '/data/email-rest-passcode',
            data: {
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                if(data.success === true) {
                    
                    document.getElementById("resetPart1").style.display = 'none';
                    document.getElementById("resetPart2").style.display = 'block';
                    document.getElementById("resetPart3").style.display = 'none';
                }
                else
                    M.toast({ html: data.error });
            },
            error: function (e) {
               
            }
        });
    },

    encrypt(password) {
        var rkEncryptionKey = CryptoJS.enc.Base64.parse('u/Gu5posvwDsXUnV5Zaq4g==');
        var rkEncryptionIv = CryptoJS.enc.Base64.parse('5D9r9ZVzEYYgha93/aUK2w==');
        var utf8Stringified = CryptoJS.enc.Utf8.parse(password);
        var encrypted = CryptoJS.AES.encrypt(password, rkEncryptionKey, {mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: rkEncryptionIv});
        var ciphertext = encrypted.ciphertext.toString(CryptoJS.enc.Base64);

        return ciphertext;
    },

    validatePasscode(){
        var that = this;
        var passcode = document.getElementById('passcode').value;
        $.ajax({
            url: '/data/validate-passcode',
            data: {
                passcode: that.encrypt(passcode)
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                if(data.success === true) {
                    
                    document.getElementById("resetPart1").style.display = 'none';
                    document.getElementById("resetPart2").style.display = 'none';
                    document.getElementById("resetPart3").style.display = 'block';

                    var select = document.getElementById('reset-select-user');
                    var html = '';
                    data.users.forEach( u => {
                        html += `<option value="${u}">${u}</option>`;
                    })

                    select.innerHTML = html;
                    M.FormSelect.init(select, {});
                }
                else
                    M.toast({ html: "Incorrect passcode or passcode expired" });
            },
            error: function (response) {
            }
        });
    },

    updatePassword() {
        var that = this;
        var valid = this.validateResetPassword();
        if(!valid)
            return;

        var passcode = document.getElementById('passcode').value;
        var newPassword = document.getElementById("newResetPassword").value;
        var user = document.getElementById("reset-select-user").value;

        $.ajax({
            url: '/data/reset-password',
            data: {
                user: user,
                passcode: that.encrypt(passcode),
                newPassword: that.encrypt(newPassword)
            },
            dataType: 'json',
            type: 'POST',
            
            success: function (data) {
                if(data.success === true) {
                    var modalEl = document.getElementById('reset-password-modal');
                    var modal = M.Modal.init(modalEl);
                    modal.close();
                    M.toast({ html: "Password saved" });
                }
                else
                    M.toast({ html: data.error });
            },
            error: function (response) {
            }
        });
    },

    validateResetPassword: function () {
        var iChars = "`~!@#$%^&*()_+=[]{}:,<>./*\\\'\"";
        
        var newPasswordEl = document.getElementById("newResetPassword");
        var newPassword = newPasswordEl.value;
        var newPasswordHelperTextEl = document.querySelector("#newResetPassword ~ .helper-text");
        var helperTextNew = '';

        var confirmPasswordEl = document.getElementById("confirmResetPassword");
        var confirmPassword = confirmPasswordEl.value;
        var confirmPasswordHelperTextEl = document.querySelector("#confirmResetPassword ~ .helper-text");
        var helperTextConfirm = '';

        if(newPassword.length < 8 || newPassword.length > 20)
            helperTextNew = '{Literal}Password must be at least 8 characters long{/Literal}';
        else if(!newPassword.match(/^(?=.*[A-Z])/))
            helperTextNew = '{Literal}Password must include one uppercase letter{/Literal}';
        else if(!newPassword.match(/^(?=.*[a-z])/))
            helperTextNew = '{Literal}Password must include one lowercase letter{/Literal}';
        else if(!newPassword.match(/^(?=.*\d)/))
            helperTextNew = '{Literal}Password must include one number{/Literal}';
        else if(!newPassword.match(/[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/))
            helperTextNew = '{Literal}Password must include one special character{/Literal}';

        var valid = true;
        newPasswordHelperTextEl.innerText = helperTextNew;
        newPasswordEl.classList = '';
        if(helperTextNew == '') {
            newPasswordEl.classList.add('valid');
            if(newPassword != confirmPassword) {
                helperTextConfirm = '{Literal}Confirm password doesn\'t match{/Literal}';
                confirmPasswordHelperTextEl.innerText = helperTextConfirm;
                confirmPasswordEl.classList.add('invalid');
                valid = false;
            }
        }
        else {
            newPasswordEl.classList.add('invalid');
            valid = false;
        }

        return valid;
    },
});
