/* eslint-disable */
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Modal, ActivityIndicator } from 'react-native';
import IDCard from './src/native/IDCard';

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

const tryIt = async (times, cb, delay) => {
  let err;
  for (let i = 0; i < times; ++i) {
    try {
      return await cb();
    } catch (e) {
      err = e;
    }
    if (delay) {
      await sleep(delay);
    }
  }
  if (err) {
    throw err;
  }
};

export default class App extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      scanning: false,
      scanned: false,
      result: {},
    };
  }

  async scan() {
    try {
      await IDCard.open();
      await tryIt(10, async () => await IDCard.authenticate(150), 10);
      return await tryIt(10, async () => await IDCard.read(2300), 10);
    } finally {
      await IDCard.close();
    }
  }


  render() {

    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>Changes you make will automatically reload.</Text>
        <Text>Shake your phone to open the developer menu.</Text>
        <Modal
          animationType="slide"
          transparent
          visible={this.state.scanned}
          onRequestClose={() => {
            this.setState({
              scanned: false,
            });
          }}
        >
          <Text>{ JSON.stringify(this.state.result) }</Text>
        </Modal>
        <ActivityIndicator animating={this.state.scanning} />
        <TouchableOpacity onPress={() => {
          this.setState({
            scanning: true,
          }, () => {
            this.scan().then((res) => {
              console.log(res);
              const {
                peopleName, sex, people, birthDay, addr, idcard, department,
              } = res;
              this.setState({
                result: {
                  peopleName, sex, people, birthDay, addr, idcard, department,
                },
                scanning: false,
                scanned: true,
              });
            }).catch((err) => {
              console.log(err);
              this.setState({
                result: err,
                scanning: false,
                scanned: true,
              });
            });
          });
        }}
        >
          <Text>扫描身份证</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
