text: import React, { useState, useEffect } from 'react';
  
  import { Button, Modal } from '@material-ui/core';
  
  import { DataService, FieldTypes } from '../../utils/data';
  import { UserService } from '../../utils/user';
  
  let stream;
  
  function getModalStyle() {
    const top = 50;
    const left = 50;
  
    return {
      top: `${top}%`,
      left: `${left}%`,
      transform: `translate(-${top}%, -${left}%)`,
      position: 'absolute'
    };
  }
  
  function DesktopCamera(props) {
  
    const [modalStyle] = useState(getModalStyle);
  
    useEffect(() => {
      setTimeout(() => {
        let video = document.querySelector("#vidjao");
        if (!video) return;
        navigator.mediaDevices.getUserMedia({ video: true, audio: false })
          .then(st => {
            stream = st;
            video.srcObject = st;
          });
      }, 500);
    });
  
    return (
      <Modal
        open={true}
        onClose={() => {
          if (props.onClose) props.onClose();
          if (stream) stream.getTracks().forEach(track => track.stop());
        }}
      >
        <div style={modalStyle}>
          <div>
            <video id="vidjao" autoPlay></video>
            <canvas id="canvas" style={{display:'none'}}></canvas>
          </div>
          <div style={{ textAlign: 'center' }}>
            <Button variant="contained" color="primary"
              onClick={() => {
                if (!UserService.isSignedIn()) return;
  
                let video = document.querySelector("#vidjao");
                video.height = 128;
                video.width = 128;
  
                let canvas = document.querySelector("#canvas");
                canvas.height = video.videoHeight;
                canvas.width = video.videoWidth;
                canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
  
                if (stream) stream.getTracks().forEach(track => track.stop());
  
                const img = canvas.toDataURL().replace('data:image/png;base64,', '');
  
                window.dispatchEvent(new CustomEvent("refreshAppBar", { detail: { picture: img } }));
  
                if (props.onClose) props.onClose();
  
                DataService.update('contact',
                  UserService.getUserId(),
                  {
                    'entityimage': { 'type': FieldTypes.Image, 'content': img }
                  });
              }}>
              Capture
            </Button>
            <Button variant="contained" style={{ marginLeft: '10px' }}
              onClick={() => {
                if (stream) stream.getTracks().forEach(track => track.stop());
                if (props.onClose) props.onClose();
              }}
            >Cancel</Button>
          </div>
        </div>
      </Modal>
    );
  }
  
  export default DesktopCamera;
  