import { NativeModules, Platform } from 'react-native';
import type { FaceExtract } from './FaceExtract';
import type { FaceVerify } from './FaceVerify';

const LINKING_ERROR =
  `The package '@biopassid/face-sdk-react-native' doesn't seem to be linked. Make sure: \n\n` +
  Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
  '- You rebuilt the app after installing the package\n' +
  '- You are not using Expo Go\n';

const FaceSdkReactNative = NativeModules.FaceSdkReactNative
  ? NativeModules.FaceSdkReactNative
  : new Proxy(
      {},
      {
        get() {
          throw new Error(LINKING_ERROR);
        },
      }
    );

export function startRecognition(licenseKey: string): void {
  try {
    FaceSdkReactNative.startRecognition(licenseKey);
  } catch (error) {
    console.error(`Unknown error: ${error}`);
  }
}

export function closeRecognition(): void {
  try {
    FaceSdkReactNative.closeRecognition();
  } catch (error) {
    console.error(`Unknown error: ${error}`);
  }
}

export async function extract(artifact: string): Promise<FaceExtract | null> {
  try {
    const extract: FaceExtract | null =
      await FaceSdkReactNative.extract(artifact);
    return extract;
  } catch (error) {
    console.error(`Unknown error: ${error}`);
    return null;
  }
}

export async function verify(
  templateA: string,
  templateB: string
): Promise<FaceVerify | null> {
  try {
    const verify: FaceVerify | null = await FaceSdkReactNative.verify(
      templateA,
      templateB
    );
    return verify;
  } catch (error) {
    console.error(`Unknown error: ${error}`);
    return null;
  }
}
