import React from 'react';
import { View, Alert, Vibration } from 'react-native';
import { RNCamera } from 'react-native-camera';

export default class QRCodeScanner extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isScanning: true,
      borderColor: '#ff0000'
    };
  }

  handleBarCodeRead(data) {
    if (this.state.isScanning) {
      Vibration.vibrate();
      this.setState({ isScanning: false, borderColor: '#00ff00' });
      this.camera.pausePreview();

      const error = this.props.onRead(data);
      if (error) {
        const onPress = () => {
          this.camera.resumePreview();
          this.setState({ isScanning: true, borderColor: '#ff0000' });
        };
        Alert.alert(error, 'Please try again', [{ text: 'OK', onPress }]);
      }
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <RNCamera
          ref={ref => { this.camera = ref; }}
          style={styles.preview(this.state.borderColor)}
          type={RNCamera.Constants.Type.back}
          permissionDialogTitle={'Camera Access Required'}
          permissionDialogMessage={'Tagfer requires Camera access for barcode scanning'}
          captureAudio={false}
          doNotSave
          onBarCodeRead={({ data }) => this.handleBarCodeRead(data)}
          barCodeTypes={[RNCamera.Constants.BarCodeType.qr]}
        />
      </View>
      
    );
  }
}

const styles = {
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center'
  },
  preview: (borderColor) => ({
    flex: 0.45,
    marginHorizontal: 10,
    borderWidth: 3,
    borderColor
  })
};
