{"size": 4726, "ext": "js", "max_stars_repo_path": "src/pages/registerUser/index.js", "max_stars_repo_name": "crismantovani/TF005-Avanade", "max_stars_repo_stars_event_min_datetime": "2021-04-12T14:36:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T14:36:40.000Z", "max_issues_repo_path": "src/pages/registerUser/index.js", "max_issues_repo_name": "crismantovani/TF005-Avanade", "max_issues_repo_issues_event_min_datetime": "2021-04-12T16:42:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T06:39:43.000Z", "max_forks_repo_path": "src/pages/registerUser/index.js", "max_forks_repo_name": "crismantovani/TF005-Avanade", "max_forks_repo_forks_event_min_datetime": "2021-04-20T13:11:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T18:18:36.000Z"}
{"max_stars_count": 1, "max_issues_count": 44, "max_forks_count": 6, "avg_line_length": 28.8170731707, "max_line_length": 142, "alphanum_fraction": 0.5763859501}
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import Header from '../../components/Header';
import Footer from '../../components/Footer';
import FaceCapture from '../../components/FaceCapture/FaceCapture';
import client from '../../utils/APIconfig';
import Modal from '../../components/Modal';

const RegisterUser = () => {
  const [userData, setUserData] = useState({
    fullName: '',
    function: '',
  });
  const [loading, setLoading] = useState(false);
  const personGroupId = 'avanade';
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalMessage, setModalMessage] = useState('');
  const [sendModalType, setSendModalType] = useState('');
  const history = useHistory();

  const handleResponseModal = (modalVisibility, modalType, message) => {
    setIsModalVisible(modalVisibility);
    setSendModalType(modalType);
    setModalMessage(message);
  };

  const addFaceToUser = (user, image) => {
    client.personGroupPerson.addFaceFromStream(personGroupId, user.personId, image)
      .then((userFace) => {
        if (userFace.persistedFaceId) {
          trainingFace();
        } else {
          handleResponseModal(true, 'error', 'Face não cadastrada, tente novamente!');
          setLoading(false);
        }
      })
      .catch((error) => {
        handleResponseModal(true, 'error', error.message);
        setLoading(false);
      });
  };

  const trainingFace = () => {
    try {
      client.personGroup.train(personGroupId);
      handleResponseModal(true, 'success', 'Usuário Cadastrado com Sucesso');
      setLoading(false);
    } catch (err) {
      handleResponseModal(true, 'error', err.message);
      setLoading(false);
    }
  };

  const createUser = (image) => {
    client.personGroupPerson.create(personGroupId, {
      name: userData.fullName, userData: userData.function,
    })
      .then((user) => {
        if (!userData.fullName && !userData.function) {
          handleResponseModal(true, 'error', 'Dados insuficientes para completar o cadastro');
          setLoading(false);
        } else {
          addFaceToUser(user, image);
        }
      })
      .catch((error) => {
        handleResponseModal(true, 'error', error.message);
        setLoading(false);
      });
  };

  const detectFace = (image) => {
    client.face.detectWithStream(image, {
      returnFaceId: true,
      recognitionModel: 'recognition_03',
    })
      .then((response) => {
        if (response.length === 0) {
          handleResponseModal(true, 'error', 'Sua Face ID não foi detectada, tente novamente! Certifique-se que sua face está desimpendida');
          setLoading(false);
        } else {
          const faceId = response[0].faceId;
          identifyFace(faceId, image);
        }
      })
      .catch((error) => {
        handleResponseModal(true, 'error', error.message);
        setLoading(false);
      });
  };

  const identifyFace = (faceId, image) => {
    client.face.identify([faceId], {
      personGroupId,
      maxNumOfCandidatesReturned: 1,
      confidenceThreshold: 0.8,
    })
      .then((face) => {
        if (!face[0].candidates.length) {
          createUser(image);
        } else {
          handleResponseModal(true, 'error', 'Sua Face ID já está cadastrada no sistema');
          setLoading(false);
        }
      })
      .catch((error) => {
        handleResponseModal(true, 'error', error.message);
        setLoading(false);
      });
  };

  const authenticateFace = (image) => {
    if (image) {
      fetch(image)
        .then((res) => res.blob())
        .then((blob) => {
          const file = new File([blob], 'Image', {
            type: 'image/png',
          });
          detectFace(file);
        })
        .catch((error) => {
          handleResponseModal(true, 'error', error.message);
          setLoading(false);
        });
    }
  };

  return (
    <>
    {isModalVisible ? (
      <Modal
        modalType={sendModalType}
        modalText={modalMessage}
        onClose={() => {
          setIsModalVisible(false);
          if (modalMessage.includes('Sua Face ID já está cadastrada no sistema') || modalMessage.includes('Usuário Cadastrado com Sucesso')) {
            history.push({
              pathname: '/',
            });
          }
        }}
      />
    ) : null}
    <Header />
    <main>
      <div className='form-container'>
        <FaceCapture
          label="Cadastrar"
          setUserData={setUserData}
          userData={userData}
          loading={loading}
          setLoading={setLoading}
          authenticateFace={authenticateFace}
        />
      </div>
    </main>
    <Footer />
  </>
  );
};

export default RegisterUser;
