/**
 * React Native Full App (https://store.enappd.com/product/react-native-full-app)
 *
 * Copyright © 2019-present Enappd. All rights reserved.
 *
 * This source code is licensed as per the terms found in the
 * LICENSE.md file in the root directory of this source tree.
 */

import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import * as Permissions from 'expo-permissions';
import Constants from 'expo-constants';
import { Container } from 'native-base';
import HeaderCommon from '../../components/common/header';
import { NavigationDrawerScreenProps } from 'react-navigation-drawer';
interface Iprops extends NavigationDrawerScreenProps {
}
export default class BarcodeScannerExample extends React.Component<Iprops> {
  state = {
    hasCameraPermission: null,
    scanned: false,
  };

  async componentDidMount() {
    const hasPermission = await Permissions.getAsync('camera', 'cameraRoll');
    if (hasPermission.status !== 'granted') {
      const { status } = await Permissions.askAsync('camera', 'cameraRoll');
      this.setState({ hasCameraPermission: status === 'granted' });
    }else{
      this.setState({ hasCameraPermission: true });
    }
  }
  toggleMenu = () => this.props.navigation.toggleDrawer();
  render() {
    const { hasCameraPermission, scanned } = this.state;

    if (hasCameraPermission === null) {
      return <Text>Requesting for camera permission</Text>;
    }
    if (hasCameraPermission === false) {
      return <Text>No access to camera</Text>;
    }
    return (
      <Container>
        <HeaderCommon title='Bar Code Scanner' toggleMenu={this.toggleMenu} />
        <View
          style={{
            flex: 1,
            justifyContent: 'flex-end',
          }}>
          <BarCodeScanner
            onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned}
            style={StyleSheet.absoluteFillObject}
          />

          {scanned && (
            <Button
              title={'Tap to Scan Again'}
              onPress={() => this.setState({ scanned: false })}
            />
          )}
        </View>
      </Container>
    );
  }

  handleBarCodeScanned = ({ type, data }) => {
    this.setState({ scanned: true });
    alert(`Bar code with type ${type} and data ${data} has been scanned!`);
  };
}