import React, { createContext, FC, useContext, useState } from "react"; import { ArgsType } from "../@types/ArgsType"; import { onErrorType, onSuccessType } from "../@types/ResultType"; import { ResultType } from "../@types/ResultTypes"; import { askPermission } from "../utils/permissions"; import { Platform } from "react-native"; //@ts-ignore import { startLiveness3d } from "../OitiExpoLiveness3dModule"; export const SCREEN = Object.freeze({ INSTRUCTION_VIEW: 1, PERMISSION_VIEW: 2, } as const); interface Liveness3DContextType { screen: number; setScreen: React.Dispatch>; navigation: any; setNavigation: React.Dispatch>; options: ArgsType | undefined; setOptions: React.Dispatch>; onLiveness3DError: (error: onErrorType) => void; onLiveness3DSuccess: (result: onSuccessType) => void; onBack: () => any; onAskPermission: () => any; startLiveness: () => any; callbackView: string; setCallbackView: React.Dispatch>; } const Liveness3DContext = createContext( undefined ); export const Liveness3DProvider: FC = ({ children, onError, onSuccess, }) => { const [screen, setScreen] = useState(1); const [navigation, setNavigation] = useState(); const [options, setOptions] = useState(); const [callbackView, setCallbackView] = useState(""); const onLiveness3DError = (error: onErrorType) => { onError(error); }; const onLiveness3DSuccess = (result: onSuccessType) => { onSuccess(result); }; function onBack() { switch (screen) { case SCREEN.INSTRUCTION_VIEW: onLiveness3DError({ code: "0", message: "RESULT_CANCELED" }); break; case SCREEN.PERMISSION_VIEW: setScreen(1); break; } } function startLiveness() { if (options) { startLiveness3d(options) .then((result) => { { if (Platform.OS == "android") { //@ts-ignore onSuccess(JSON.parse(result) as onSuccessType); } else { onSuccess(result as onSuccessType); } } }) .catch((error) => { onError(error as onErrorType); }); } } function onAskPermission() { askPermission().then((result) => { result === true && startLiveness(); result === false && setScreen(1); }); } const contextValue: Liveness3DContextType = { screen, setScreen, navigation, setNavigation, onLiveness3DError, onLiveness3DSuccess, onBack, options, setOptions, startLiveness, onAskPermission, callbackView, setCallbackView, }; return ( //@ts-ignore {children} ); }; export const useLiveness3DContext = (): Liveness3DContextType => { const context = useContext(Liveness3DContext); if (!context) { throw new Error( "useLiveness3DContext must be used within a Liveness3DProvider" ); } return context; }; export default Liveness3DContext;