/*
    Предрейсовые осмотры - мобильное приложение
    Универсальный хук обработки данных встроенного сканера для экранов с полями ввода
*/

//---------------------
//Подключение библиотек
//---------------------

const React = require('react'); //React и хуки
const { resolveScanTarget, getNextInOrder } = require('../utils/scanInputTargetResolver'); //Резолвер цели для сканера

//-----------
//Тело модуля
//-----------

//Хук формирования обработчика данных от встроенного сканера
function useScanInputHandler(options) {
    const { allowedFieldIds, focusedFieldRef, expectedNextTargetRef, setFieldValue, focusField, parseSegments, onSubmitForm } = options;

    const handleHardwareScan = React.useCallback(
        barcode => {
            const segments = parseSegments(barcode);
            if (segments.length === 0) {
                return;
            }

            const allowed = Array.isArray(allowedFieldIds) ? allowedFieldIds : [];
            if (allowed.length === 0) {
                return;
            }

            const focused = focusedFieldRef.current;
            let targetField = resolveScanTarget(focused, allowed);
            if (targetField == null) {
                return;
            }

            let lastTargetField = targetField;
            for (let i = 0; i < segments.length; i++) {
                const value = segments[i];
                setFieldValue(targetField, value);
                lastTargetField = targetField;
                const nextField = getNextInOrder(targetField, allowed);
                if (nextField && i < segments.length - 1) {
                    expectedNextTargetRef.current = nextField;
                    focusedFieldRef.current = nextField;
                    targetField = nextField;
                } else if (!nextField) {
                    focusedFieldRef.current = null;
                    expectedNextTargetRef.current = null;
                    if (typeof onSubmitForm === 'function') {
                        onSubmitForm();
                    }
                    return;
                } else {
                    expectedNextTargetRef.current = nextField;
                    focusedFieldRef.current = nextField;
                    focusField(nextField);
                    return;
                }
            }
            focusedFieldRef.current = lastTargetField;
            focusField(lastTargetField);
        },
        [allowedFieldIds, focusedFieldRef, expectedNextTargetRef, setFieldValue, focusField, parseSegments, onSubmitForm]
    );

    return handleHardwareScan;
}

//----------------
//Интерфейс модуля
//----------------

module.exports = useScanInputHandler;
