const SelfRegistrationUsernameValidator = function (allowChangeUsername) {

    const isAllowChangeUsernameEnabled = allowChangeUsername === '1';

    const getMaxLengthFromRegex = (regexPattern) => {
        const match = /\{(\d+),(\d+)\}\$$/.exec(regexPattern);
        
        if (match) {
            return parseInt(match[2], 10);
        }
        
        return undefined;
    }


    const shouldSkipUsernameValidation = (defaultUsername, usernameRegex) => {
        if (isAllowChangeUsernameEnabled) {
            return false;
        }
        
        const maxLength = getMaxLengthFromRegex(usernameRegex);
        
        if (!maxLength) {
            alert("Unable to complete your request. Please check your entry and retry. If the problem persists, contact us for assistance.");
            
            return false;
        }
        
        return defaultUsername.length > maxLength;
    }

    const handleUsernameChange = () => {
        const usernameRegexValue = $('#UsernameRegex').val();
        const defaultUsername = $("#DefaultUsername").val();
        
        if (shouldSkipUsernameValidation(defaultUsername, usernameRegexValue)) {
            $('#Username').removeAttr('readonly');
        }
    }

    return {
        shouldSkipUsernameValidation: shouldSkipUsernameValidation,
        handleUsernameChange: handleUsernameChange,
    }
}

$(document).ready(function () {
    const selfRegistrationConfirm =
        new SelfRegistrationUsernameValidator($('#SelfRegistrationAllowChangeUsername').val());

    selfRegistrationConfirm.handleUsernameChange();
});