import * as React from 'react';
import { View, TextInput, Keyboard } from 'react-native';

import env from '~/config/env';
import { testIdProps } from '~/test/utils';

import { ChildComponentProps } from './scanner.props';
import { scannerHidStyles as styles } from './scanner.styles';

const { BARCODE_SCANNER_VERBOSE } = env;

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

/**
 * Component in charge to receive barcode read by HID scanner.
 *
 * @param {func} onBarcodeDetected Callback executed when the scanner reads a barcode.
 */
export function ScannerHid(props: ChildComponentProps) {
  const { onBarcodeDetected } = props;
  const textInputRef = React.useRef<TextInput>();
  const temporaryValueRef = React.useRef<string>();

  function handleBarcodeSubmit() {
    LOG('-- Barcode read:', temporaryValueRef.current);
    onBarcodeDetected(temporaryValueRef.current);
    temporaryValueRef.current = '';
    textInputRef.current.clear();
  }

  function handleData(barcode: string) {
    temporaryValueRef.current = barcode;
  }

  React.useEffect(function () {
    // Hide that keyboard!
    Keyboard.dismiss();
  }, []);

  return (
    <View style={styles.container}>
      <TextInput
        ref={textInputRef}
        autoFocus
        clearTextOnFocus
        autoCapitalize="none"
        blurOnSubmit={false}
        onChangeText={handleData}
        onSubmitEditing={handleBarcodeSubmit}
        {...testIdProps('scanner-hid-textinput')}
      />
    </View>
  );
}
