export function handleQuantityChange(params) {
    const {
        quantityInput,
        action,
        value,
        context,
        charity = false,
        entryNumber,
        onQuantityChange,
        debounceQuantityChange,
        onRemoveQuantityDisable,
        parentWrap,
    } = params;

    let newValue = value;

    switch (action) {
        case 'plus':
            newValue = Number.parseInt(value, 10) + 1;
            if (newValue) {
                updateQuantity(quantityInput, newValue, parentWrap);
                debounceQuantityChange(
                    entryNumber,
                    newValue,
                    quantityInput,
                    context,
                    onQuantityChange
                );
            }
            break;
        case 'minus':
            newValue = Number.parseInt(value, 10) - 1;
            if (newValue > 0) {
                updateQuantity(quantityInput, newValue, parentWrap);
                debounceQuantityChange(
                    entryNumber,
                    newValue,
                    quantityInput,
                    context,
                    onQuantityChange
                );
            } else {
                if (typeof onRemoveQuantityDisable === 'function') {
                    onRemoveQuantityDisable();
                }
            }
            break;
        case 'remove':
            newValue = 0;
            if (!charity) updateQuantity(quantityInput, newValue, parentWrap);
            debounceQuantityChange(entryNumber, newValue, quantityInput, context, onQuantityChange);
            break;
        default:
            if (+newValue !== 0) {
                updateQuantity(quantityInput, newValue, parentWrap);
                debounceQuantityChange(
                    entryNumber,
                    newValue,
                    quantityInput,
                    context,
                    onQuantityChange
                );
            }
            break;
    }
}

export function updateQuantity(quantityInput, value, parentWrap) {
    if (quantityInput.is('input')) {
        quantityInput.val(value);
    } else {
        quantityInput.text(value);
    }
    quantityInput.attr('value', value);

    if (parentWrap) {
        const $card = quantityInput.closest(parentWrap);
        if ($card.length) {
            $card.attr('data-quantity', value);
        }
    }
}
