import { formatGc16 } from './gift-cards-utils';
import { clearErrorText, showErrorText } from './validation';

export function createGcNumberInputHandler({
    fieldSelector,
    fieldErrorClass,
    errorTextSelector,
    ariaInvalidAttr,
}) {
    return function handleGcNumberInput(e) {
        const input = e.currentTarget;
        const $input = $(input);

        const canTrack = typeof input.selectionStart === 'number';
        const atEnd = canTrack && input.selectionStart === input.value.length;

        const hadErr = $input.closest(fieldSelector).hasClass(fieldErrorClass);

        input.value = formatGc16(input.value);

        if (hadErr) {
            clearErrorText(
                $input,
                fieldSelector,
                errorTextSelector,
                fieldErrorClass,
                ariaInvalidAttr
            );
        }

        if (atEnd && typeof input.setSelectionRange === 'function') {
            input.setSelectionRange(input.value.length, input.value.length);
        }
    };
}

export function digitsOnlyKeypress(e) {
    if (!/\d/.test(String.fromCharCode(e.which || e.keyCode))) {
        e.preventDefault();
    }
}

export function handleGcNumberBlur(
    e,
    { fieldSelector, errorTextSelector, errorClass, ariaInvalidAttr, numberMessage }
) {
    const $input = $(e.currentTarget);
    const len = String($input.val() || '').replace(/\D/g, '').length;

    clearErrorText($input, fieldSelector, errorTextSelector, errorClass, ariaInvalidAttr);

    if (len < 16) {
        showErrorText(
            $input,
            numberMessage,
            fieldSelector,
            errorTextSelector,
            errorClass,
            ariaInvalidAttr
        );
    }
}

export function handleGcPinInput(
    e,
    { fieldSelector, errorTextSelector, errorClass, ariaInvalidAttr }
) {
    const input = e.currentTarget;
    const $input = $(input);

    const hadErr = $input.closest(fieldSelector).hasClass(errorClass);
    input.value = String(input.value || '')
        .replace(/\D/g, '')
        .slice(0, 8);

    if (hadErr) {
        clearErrorText($input, fieldSelector, errorTextSelector, errorClass, ariaInvalidAttr);
    }
}

export function handleGcPinKeypress(e) {
    if (!/\d/.test(String.fromCharCode(e.which || e.keyCode))) e.preventDefault();
}

export function handleGcPinBlur(
    e,
    { fieldSelector, errorTextSelector, errorClass, ariaInvalidAttr, pinMessage }
) {
    const $input = $(e.currentTarget);
    const length = String($input.val() || '').replace(/\D/g, '').length;

    clearErrorText($input, fieldSelector, errorTextSelector, errorClass, ariaInvalidAttr);

    if (length < 8) {
        showErrorText(
            $input,
            pinMessage,
            fieldSelector,
            errorTextSelector,
            errorClass,
            ariaInvalidAttr
        );
    }
}
