const MAX_NAME_LEN = "255";
const MIN_NAME_LEN = "1";
const MIN_PHONE_LEN = '8';
const MAX_PHONE_LEN = '12';
const MESSAGES = {
    NAME_HINT: "Masukkan nama anda",
    PHONE_HINT: "Masukkan nombor telefon anda",
    WRONG_NAME: "Sahkan bahawa anda sudah memasukkan nama yang betul",
    WRONG_PHONE: "Sahkan bahawa anda sudah memasukkan nombor telefon yang betul"
}
const USER_HINT_MESSAGE_ID = 'msg_for_user_in_form'
const FORBIDDEN_SYMBOLS = ['\'', '"', '#', '&', '-', '\\', '@', '!', '~', '`', '|', '/', '^', '(', '{', ';', ':'];
const PERMITTED_PHONE_SYMBOLS = /[^+0-9]/gi;
const FORMS = [];

function destroyHistory() {
    const curURL = window.location.href;
    const curTitle = document.title;

    history.pushState(null, curTitle, curURL);
    window.onpopstate = function (e) {
        e.preventDefault();
        history.scrollRestoration = 'manual';
        for (let i = 0; i < 10; i++) {
            history.pushState(null, curTitle, curURL);
        }
    }
}

for (let form of document.forms) {
    FORMS.push(form);
}

FORMS.forEach(function (form, i) {
    if (
        null === form.querySelector("input[name='name']") ||
        null === form.querySelector("input[name='phone']")
    ) return;
    const prepareNameField = form.querySelector("input[name='name']")
    prepareNameField.setAttribute('type', 'text')
    prepareNameField.setAttribute('maxlength', MAX_NAME_LEN)
    prepareNameField.setAttribute('minlength', MIN_NAME_LEN)
    prepareNameField.setAttribute('autocomplete', 'off')
    prepareNameField.addEventListener('input', function (e) {
        if (FORBIDDEN_SYMBOLS.includes(e.data)) {
            prepareNameField.value = prepareNameField.value.replace(e.data, '')
        }
    })
    prepareNameField.addEventListener('focus', function (e) {
        showMessageOnFocus(prepareNameField, MESSAGES.NAME_HINT)
    })
    prepareNameField.addEventListener('focusout', function (e) {
        clearMessages(USER_HINT_MESSAGE_ID);
    })

    const preparePhoneField = form.querySelector("input[name='phone']")
    preparePhoneField.setAttribute('type', 'tel')
    preparePhoneField.setAttribute('maxlength', MAX_PHONE_LEN)
    preparePhoneField.setAttribute('minlength', MIN_PHONE_LEN)
    preparePhoneField.setAttribute('autocomplete', 'off')
    preparePhoneField.addEventListener('input', function (e) {
        preparePhoneField.value = preparePhoneField.value.replace(PERMITTED_PHONE_SYMBOLS, '')
    })
    preparePhoneField.addEventListener('focus', function (e) {
        showMessageOnFocus(preparePhoneField, MESSAGES.PHONE_HINT)
    })
    preparePhoneField.addEventListener('focusout', function (e) {
        clearMessages(USER_HINT_MESSAGE_ID);
    })
    form.addEventListener('submit', function (e) {
        e.preventDefault()
        handleForm(this)
    })
})

function handleForm(form) {
    const NAME_FIELD = form.querySelector("input[name='name']")
    const PHONE_FIELD = form.querySelector("input[name='phone']")
    const VALID_NAME = validateName(NAME_FIELD.value)
    const VALID_PHONE = validatePhone(PHONE_FIELD.value)
    clearMessages(USER_HINT_MESSAGE_ID);
    if (false === VALID_NAME) {
        showMessageOnError(NAME_FIELD, MESSAGES.WRONG_NAME)
        return false;
    }
    if (false === VALID_PHONE) {
        showMessageOnError(PHONE_FIELD, MESSAGES.WRONG_PHONE)
        return false
    }
    if (false !== VALID_PHONE && false !== VALID_NAME) {
        form.querySelector("input[name='name']").value = VALID_NAME
        form.querySelector("input[name='phone']").value = VALID_PHONE
        submitForm(form)
    }
}

function clearMessages(id) {
    const ELEMENT_PHONE_MESSAGE_ON_PAGE = document.querySelectorAll('#' + id)
    if (ELEMENT_PHONE_MESSAGE_ON_PAGE !== undefined) {
        ELEMENT_PHONE_MESSAGE_ON_PAGE.forEach(function (element, i) {
            element.remove()
        })
    }
}

function submitForm(form) {
    destroyHistory();
    form.submit()
}

function validateName(name) {
    return handleUserName(name)
}

function handleUserName(name) {
    FORBIDDEN_SYMBOLS.forEach(function (symbol, i) {
        name = name.replace(symbol);
    })
    return (name.length >= MIN_NAME_LEN && name.length <= MAX_NAME_LEN) ? name : false
}

function validatePhone(phone) {
    return handlePhoneNum(phone);
}

function handlePhoneNum(phone) {
    if (phone === '') return false;
    phone = replaceAllExceptDigits(phone)
    if (checkPhoneLength(phone) !== false) {
        return phone;
    }
    return false;
}

function replaceAllExceptDigits(phone) {
    return phone.replace(/[^+0-9]/gi, '')
}

function checkPhoneLength(phone) {
    return (phone.length >= MIN_PHONE_LEN && phone.length <= MAX_PHONE_LEN);
}

function showMessageOnError(elem, message) {
    showMessage(elem, message)
}

function showMessageOnFocus(elem, message) {
    showMessage(elem, message)
}

function showMessage(elem, message) {
    if (elem.classList.contains('js_errorMessage') !== undefined) {
        elem.classList.remove('js_errorMessage')
    }
    const newOffsetTop = elem.offsetTop - 36 + 'px'
    const newOffsetLeft = elem.offsetLeft + 'px'
    const appender = document.createElement('div')
    appender.style.backgroundColor = '#e74c3c'
    appender.style.border = '1px dashed black'
    appender.style.borderRadius = '5px'
    appender.style.color = '#fff'
    appender.style.fontFamily = 'Arial'
    appender.style.fontSize = '14px'
    appender.style.margin = '3px 0 0 0px'
    appender.style.padding = '6px 5px 5px'
    appender.style.position = 'absolute'
    appender.style.zIndex = '9999'
    appender.style.top = newOffsetTop
    appender.style.left = newOffsetLeft
    appender.textContent = message
    appender.id = USER_HINT_MESSAGE_ID
    elem.before(appender)
}