import * as React from 'react';

import env from '~/config/env';
import { bleManager, Data } from '~/services/ble-manager';
import { timing } from '~/theme';

import { ChildComponentProps } from './scanner.props';

const { BARCODE_SCANNER_VERBOSE } = env;

function LOG(...args: any[]) {
  BARCODE_SCANNER_VERBOSE && logger.log(...args);
}

/**
 * Component in charge to receive barcode read by BLE scanner.
 *
 * @param {func} onBarcodeDetected Callback executed when the scanner reads a barcode.
 */
export function ScannerBle(props: ChildComponentProps) {
  const { onBarcodeDetected } = props;
  const temporaryValueRef = React.useRef('');
  let timeout = null;

  function sendData(barcode: string) {
    onBarcodeDetected(barcode);
    temporaryValueRef.current = '';
  }

  function handleData(data: Data) {
    LOG('-- Barcode read:', data.value);

    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }

    if (data.value.length === 20 && !temporaryValueRef.current) {
      temporaryValueRef.current = data.value;
      timeout = setTimeout(function () {
        sendData(data.value);
        timeout = null;
      }, timing[0]);
    } else if (temporaryValueRef.current) {
      sendData(`${temporaryValueRef.current}${data.value}`);
    } else {
      sendData(data.value);
    }
  }

  React.useEffect(
    function () {
      bleManager.addListener('data', handleData);

      return () => bleManager.removeListener('data', handleData);
    },
    [onBarcodeDetected],
  );

  return null;
}
