import React, { Component } from 'react';
import jsQR from 'jsqr';
import { withStyles } from '@material-ui/core/styles';

import Camera from './Camera/Camera';

const styles = theme => ({
  cameraWrapper: {
    position: 'relative'
  },
  qrMarker: {
    position: 'absolute',
    height: '70%',
    margin: 'auto',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0
  }
});


const videoConstraints = {
  width: 1280,
  height: 720,
  facingMode: 'environment'
};

class ScanQRCode extends Component {
  constructor(props) {
    super(props);
    this.setWebcamActivated = this.setWebcamActivated.bind(this);
  }

     state={
       captureInterval: '',
       codeFound: false,
       webcamActive: false
     }

     componentDidMount() {
       const captureInteval = setInterval(() => this.capture(), 600);
       this.state.captureInterval = captureInteval;
     }

     setRef = (webcam) => {
       this.webcam = webcam;
     };

     setWebcamActivated() {
       this.setState({
         webcamActive: true
       });
     }

     capture = () => {
       const { webcamActive } = this.state;
       const { getPassport, transitToExternalPassport } = this.props;
       if (webcamActive) {
         const canvasElement = this.webcam.getCanvas();
         if (canvasElement) {
           const canvas = canvasElement.getContext('2d');
           const imageData = canvas.getImageData(0, 0, videoConstraints.width, videoConstraints.height);
           const code = jsQR(imageData.data, imageData.width, imageData.height, {
             inversionAttempts: 'dontInvert',
           });
           if (code) {
             this.setState({
               codeFound: true
             }, () => {
               const uid = code.chunks[3].text;
               const token = sessionStorage.getItem('token');
               if (token) {
                 getPassport(uid);
               } else {
                 transitToExternalPassport(uid);
               }
             });
           }
         }
       }
     }

     render() {
       const { codeFound, captureInterval } = this.state;
       const { classes } = this.props;
       if (codeFound) clearInterval(captureInterval);
       return (
         <div>

           <Camera
             audio={false}
             height="100%"
             ref={this.setRef}
             onUserMedia={this.setWebcamActivated}
             screenshotFormat="image/jpeg"
             width="100%"
             muted
             videoConstraints={videoConstraints}
             style={classes}
           />

         </div>
       );
     }
}

export default withStyles(styles)(ScanQRCode);
