(function (paw, utils) {
    function UsernameVerification($usernameInput, $usernameField, initialValue, settings, localization) {
        var self = this;
        this.$usernameInput = $usernameInput;
        this.$usernameField = $usernameField;
        
        this.settings = paw.lang.append({
            verifyUsernameUrl: '@Url.Action("VerifyUsername", "Users")',
            activateUserUrl: '@Url.Action("ActivateUser", "Users")',
            userEditPath: '/Users/Edit'
        }, settings || {});
        this.localization = paw.lang.append({
            yes: '@Loc.Yes',
            no: '@Loc.No',
            userAlreadyExists: '@Loc.UserAlreadyExists',
            userExists: '@Loc.UserExists',
            userAlreadyExistsNotActive: '@Loc.UserAlreadyExistsNotActive',
            userExistsNotActiveQuestion: '@Loc.UserExistsNotActiveQuestion',
            loginExistsConnectQuestion: '@Loc.LoginExistsConnectQuestion',
            loginAlreadyExists: '@Loc.LoginAlreadyExists',
            userConnectToLogin: '@Loc.UserConnectToLogin'
        }, localization || {});

        this.modelData = {
            username: initialValue
        };

        this.isActivatingUser = false;
        this.usernameInputField = null;
    }

    UsernameVerification.prototype.init = function(){
        var self = this;
        this.usernameInputField = new paw.com.Input(this.$usernameInput, 'username', this.modelData, null, function(val){
            self.clearUsernameFieldError();
        });
    };

    UsernameVerification.prototype.verifyUsername = function(success, verificationError){
        var self = this;
        return this.verify(this.modelData.username, verificationError).then(function(result){
            return self.handleVerificationResult(result, success);
        });
    };

    UsernameVerification.prototype.verify = function (username, verificationError){
        return utils.async.post(this.settings.verifyUsernameUrl, {
            Username: username
        }).catch(function(ex){
            if(!utils.value.isSet(ex)){
                console.error("No verification result");
                verificationError();
                return ex;
            }
            console.error(ex);
            return ex;
        });
    };

    UsernameVerification.prototype.clearUsernameFieldError = function(){
        this.$usernameField.find('#username-validation-error').remove();
        this.$usernameField.find('.paw-username-verification-msg').remove();
        this.$usernameField.removeClass("has-error");
    };
    
    UsernameVerification.prototype.handleVerificationResult = function(result, success){
        var self = this;

        if(!utils.value.isSet(result)){
            this.clearUsernameFieldError();
            console.error("NO VERIFICATION RESULT");
            return;
        }

        if(!paw.utils.value.isSet(result.Error)){  
            return success();
        }
        
        switch(result.Error){
            case 'USER_EXISTS':
                this.openMessagePopup({
                    id: 'user-exists',
                    text: utils.value.interpolateString(self.localization.userExists, {
                        "%S": self.modelData.username
                    }),
                    onClose: function(){
                        self.setValidationError(self.localization.userAlreadyExists);
                    }
                });
                
                break;
            case 'USER_EXISTS_NOT_ACTIVE':
                this.openMessagePopup({
                    id: 'user-exists-not-active',
                    text: utils.value.interpolateString(this.localization.userExistsNotActiveQuestion, {
                        '%S': self.modelData.username
                    }),
                    type: 'question',
                    buttons: [
                        {
                            text: this.localization.no,
                            closeOnAction: true
                        },
                        {
                            text: this.localization.yes,
                            closeOnAction: true,
                            type: 'primary',
                            action: function () {
                                self.isActivatingUser = true;
                                self.activateUser();
                            }
                        }
                    ],
                    onClose: function () {
                        if (self.isActivatingUser) {
                            return;
                        }
                        self.setValidationError(self.localization.userAlreadyExistsNotActive);
                    }
                });
                break;
            case 'LOGIN_EXISTS_CONNECTION_NOT_APPROVED':
                this.openMessagePopup({
                    id: 'connect-to-login',
                    text: utils.value.interpolateString(this.localization.loginExistsConnectQuestion, {
                        '%S': self.modelData.username
                    }),
                    type: 'question',
                    buttons: [
                        {
                            text: this.localization.no,
                            closeOnAction: true,
                            action: function(){
                                $('input[type=hidden]#CanConnectToExistingSqlLogin').val(false);
                            }
                        },
                        {
                            text: this.localization.yes,
                            closeOnAction: true,
                            type: 'primary',
                            action: function(){
                                $('input[type=hidden]#CanConnectToExistingSqlLogin').val(true);
                                success();
                            }
                        }
                    ],
                    onClose: function(){
                        if(!self.getConnectToLogin()){
                            self.setValidationError(self.localization.loginAlreadyExists);
                        }                        
                    }
                });
                break;
        }
    };

    UsernameVerification.prototype.openMessagePopup = function(settings){
        settings = paw.lang.append({
            title: '',
            destroyOnClose: true,
            showCloseButton: true,
            id: '',
            type: 'error',
            text: '',
            buttons: undefined,
            onClose: undefined
        }, utils.iterable.assertProps(settings, ['id', 'text']));
        $().customModal(settings);
    };

    UsernameVerification.prototype.setValidationError = function(text, actions){
        var self = this;
        this.clearUsernameFieldError();

        var markup = [];
        markup.push('<div id="username-validation-error">');
        markup.push('   <div>');
        markup.push('      <span class="field-validation-error text-danger">' + text + '</span>');
        markup.push('   </div>');
        if(paw.utils.value.isSet(actions) && actions.length > 0){
            markup.push('   <div>');
            paw.utils.iterable.iterate(actions, function(action){
                markup.push('<button id="' + action.id + '" type="button" class="paw-btn paw-username-error-action' + (action.styleClass? ' ' + action.styleClass : '') + '">');
                if(paw.utils.value.isSet(action.icon)){
                    markup.push('   <span class="' + action.icon + ' paw-username-error-action-icon"></span>');
                }
                markup.push('   <span>' + action.label + '</span>');
                markup.push('</button>');
            });
            markup.push('   </div>');
        }
        markup.push('</div>');
        this.$usernameInput.parent().append(markup.join('\n'));

        if(paw.utils.value.isSet(actions) && actions.length > 0){
            paw.utils.iterable.iterate(actions, function(action){
                self.$usernameField.find('button#' + action.id).on('click', function(){
                    action.onSelected(action);
                });
            });
        }

        this.$usernameField.addClass("has-error");
    };

    UsernameVerification.prototype.getConnectToLogin = function(){
        return utils.value.strToBool($('input[type=hidden]#CanConnectToExistingSqlLogin').val());
    }

    UsernameVerification.prototype.activateUser = function(){
        var self = this;
        return utils.async.post(this.settings.activateUserUrl, {
            Username: this.modelData.username
        }).then(function(activatedUser){
            window.location = self.settings.userEditPath + '?id=' + activatedUser.Id;
        });
    };

    // keeping for ref.
    UsernameVerification.prototype.compileLoginConnectMsg = function(){
        if(!this.getConnectToLogin()){
            return;
        }
        var markup = [];
        markup.push('<div class="paw-username-verification-msg">')
        markup.push('   <span class="fa fa-warning paw-username-connect-icon"></span>');
        markup.push('   <span>' + this.localization.userConnectToLogin + '</span>');
        markup.push('</div>');

        this.clearUsernameFieldError();
        this.$usernameInput.after(markup.join('\n'));
    };

    paw.view.user.UsernameVerification = UsernameVerification;
})(paw, paw.utils);