/**
 * Sample React Native App
 *
 * adapted from App.js generated by the following command:
 *
 * react-native init example
 *
 * https://github.com/facebook/react-native
 */

import React, { Component } from 'react';
import {StyleSheet, Text, View, Button, NativeModules} from 'react-native';
import AAIIOSLivenessSDK from 'react-native-aaiios-liveness-sdk';

export default class App extends Component<{}> {
  state = {
    message: '--',
    version: '',
    rootPage: true,
    sdkInitSuccess: false
  };

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    // Get SDK version
    AAIIOSLivenessSDK.sdkVersion((message) => {
      console.log("SDK version is ", message)
      this.setState({
        version: message,
      });
    });
  }

  sdkDemo() {
    /*
    /// Optional 
    // Get SDK version
    AAIIOSLivenessSDK.sdkVersion((message) => {
      console.log("SDK version is ", message)
    });
    */

    // Step 1. Initialize SDK
    // The last boolean value represents whether the Global service is enabled or not, and is set to true if it is, or false if it is not.
    // Market available value are as follows:
    // AAILivenessMarketIndonesia
    // AAILivenessMarketIndia
    // AAILivenessMarketPhilippines
    // AAILivenessMarketVietnam
    // AAILivenessMarketThailand
    // AAILivenessMarketMexico
    // AAILivenessMarketMalaysia
    // AAILivenessMarketPakistan
    // AAILivenessMarketNigeria
    // AAILivenessMarketColombia
    // AAILivenessMarketSingapore
    AAIIOSLivenessSDK.initSDKByLicense("AAILivenessMarketIndonesia", false)

    /*
    /// Optional 
    // Configure SDK detection level
    // Available levels are "EASY", "NORMAL", "HARD". Default is "NORMAL".
    // Note that this method must be called before "setLicenseAndCheck", otherwise it won't take effect.
    AAIIOSLivenessSDK.setDetectionLevel("NORMAL")
    */

    /*
    /// Optional 
    // Set wheher to detect occlusion. Default is false.
    AAIIOSLivenessSDK.setDetectOcclusion(true)
    */

    /*
    /// Optional 
    // Set action detection time interval. Default is 10s.
    // Note that this value represents the timeout for a motion,
    // not the total timeout for all motions.
    AAIIOSLivenessSDK.setActionTimeoutSeconds(10)
    */
    
    /*
    /// Optional 
    // Set the size(width) of output `img` in `onDetectionComplete`. 
    // Image size(width) should be in range [300, 1000], default image size(width) is 600(600x600).
    AAIIOSLivenessSDK.setResultPictureSize(600)
    */

    /*
    /// Optional
    // Set the action sequence. Available action type are "POS_YAW", "BLINK", "MOUTH"
    // the first boolean value indicates if the given actions should be shuffled.
    // Default action sequence ["POS_YAW", "BLINK"] and the order of them is random.
    AAIIOSLivenessSDK.setActionSequence(true, ["POS_YAW", "BLINK", "MOUTH"])
    */

    /*
    /// Optional
    // User binding (strongly recommended).
    // You can use this method to pass your user unique identifier to us, 
    // we will establish a mapping relationship based on the identifier。
    // It is helpful for us to check the log when encountering problems.
    AAIIOSLivenessSDK.bindUser("your-reference-id")
    */

    /*
    // Optional
    // If you enable this feature, the SDK will automatically upload the audit image sequence list to the server after liveness detection complete. 
    // You can obtained the 'auditImageUrl' fileld in the liveness-detection openapi response. See liveness-detection openapi for more detail.
    // 
    // The first parameter:Whether to collect audit images. Default is false.
    // The second parameter:Minimum interval time for capturing images,default interval is 400ms
    // The third parameter:Maximum number of captured images,default number is 10
    // The fourth parameter:The image width,default width is 400px
    // The fifth parameter:The image compress quality,must in [30,100],the default value is 30
    AAIIOSLivenessSDK.setAuditImageConfig(false,300,2,400,50)  
    */

    /*
    /// Optional
    //  If you enable this feature, SDK will record video during the detection process. 
    //  After the completion of the liveness process, you can retrieve the 'videoFilePath' by parse the 'additionalInfo' 
    //  in 'onDetectionComplete' callback.
    //  The video file format is .mp4. Please note that this video can only be obtained through the SDK and 
    //  cannot be obtained from the aai backend. After using the video, it is up to you to decide whether to delete the local file.
    // 
    // The first parameter:Whether to record video. Default value is false.
    // The second parameter:The maximum recording duration, in seconds, valid range [2,60], default is 60 seconds.
    AAIIOSLivenessSDK.setVideoRecorderConfig(false,60)
    */

    // Step 2. Configure your license(your server needs to call openAPI to obtain license content)
    let licenseStr = "your-license-string"
    AAIIOSLivenessSDK.setLicenseAndCheck(licenseStr, (result) => {
      if (result === "SUCCESS") {
        this.showSDKPage()
      } else {
        console.log("setLicenseAndCheck failed:", result)
        this.setState({message: result})
      }
    })

  }

  showSDKPage() {
    var config = {
      /*
      /// Optional
      showHUD: true,
      */

      /*
      /// Optional
      /// Specify which language to use for the SDK. If this value is not set,
      /// the system language will be used by default. If the system language is not supported,
      /// English will be used.
      ///
      /// The languages currently supported by sdk are as follows:
      /// 
      /// "en" "id"  "vi"  "zh-Hans"  "th"  "es"  "ms" "hi"
      language: "en",
      */
      
      /*
      /// Optional (Note from v3.0.4, this configuration item has been deprecated, please use `timeoutDurationOf3DMode` instead)
      /// Set the timeout for prepare stage, default is 50s.
      prepareTimeoutInterval: 50,
      */

      /*
      /// Optional
      /// Set the detection timeout duration of 3D mode(near/distant mode), the range of value should be [10, 60], default is 50s.
      /// If the detection cannot pass within this time duration,  the `onDetectionFailed` will be called,
      /// and the value of the "errorCode" is "fail_reason_prepare_timeout".
      ///
      /// @note This time duration does not include network request duration.
      ///
      timeoutDurationOf3DMode: 50,
      */

      /*
      /// Optional
      // Set the color of the round border in the avatar preview area. Default is clear color(#00000000).
      roundBorderColor: "#00000000",
      */
      
      /*
      /// Optional
      // Set the color of the ellipse dashed line that appears during the liveness detection. Default is white color.
      ellipseLineColor: "#FFFFFF",
      */
      
      /*
      /// Optional
      // Whether to animate the presentation. Default is true.
      animated: true,
      */

      /*
      /// Optional
      // Whether to display animation images. Default is true. If you set false, then animation images will be hidden.
      showAnimationImgs: true
      */
      
     /*
      /// Optional
      // Whether to allow to play prompt audio. Default is true.
      playPromptAudio: true,
      */

      /*
      /// Optional
      /// The color of the ellipse border in 3D mode(near/distant mode). Default is #5BC413.
      ellipseBorderCol3D: "#0000FF",
      */
      
      /*
      /// Optional
      /// The normal color of the ellipse border in 3D mode(near/distant mode). The default is #F5F5F5.
      /// @since 3.3.0
      normalEllipseBorderCol3D: "#5BC413",
      */
     
      /*
      /// Optional
      /// The color of the inner ellipse animation line of the 3D mode(near/distant mode). Default is #5BC413.
      innerEllipseLineCol3D: "#FF0000",
      */
      
      /*
      /// Optional
      /// Specify AAILoadingHud brand color. Default is #5BC413.
      /// @since 3.4.0
      hudBrandColor: "#5BC413",
      */

      /*
     /// Whether to mark the action of tapping back button as "USER_GIVE_UP". The default is false. If you set true, the `onDetectionFailed`
     /// will be called when the user taps the top left back button while liveneness detection is running.
     recordUserGiveUp: false,
      */

     /*
     /// An optional string value used to conveniently query liveness detection results.
     /// Call the `/liveness/generate-signature-id` API to generate this value, then assign it to
     /// this field before starting a new liveness flow.
     ///
     /// @warning The value must be unique per liveness flow. Passing a previously used value will result in a parameter error in SDK.
     ///
     /// @since 3.6.0
     signatureId: "my-unique-signature-id",
     */
    }

    // Step 3. Configure callback
    var callbackMap = {
      // Optional
      onCameraPermissionDenied: (errorKey, errorMessage) => {
        console.log(">>>>> onCameraPermissionDenied", errorKey, errorMessage)
        this.setState({message: errorMessage})
      },

      // Optional
      /*
      For `livenessViewBeginRequest` and `livenessViewEndRequest`, 
      these two methods are only used to tell you that the SDK is going to start sending network requests and end network requests, 
      and are usually used to display and close the loadingView, that is,  if you pass showHUD: false, then you should in method `livenessViewBeginRequest` to show your customized loading view
      and close loading view in method `livenessViewEndRequest`. If you pass showHUD: true, then you do nothing in these two methods.
      */
     /*
      livenessViewBeginRequest: () => {
        console.log(">>>>> livenessViewBeginRequest")
      },

      // Optional
      livenessViewEndRequest: () => {
        console.log(">>>>> livenessViewEndRequest")
      },
      */

      // Required
      onDetectionComplete: (livenessId, base64Img, additionalInfo) => {
        console.log(">>>>> onDetectionComplete:", livenessId, additionalInfo)
         /*
          You need to give the livenessId to your server, then your server will call the anti-spoofing api to get the score of this image.
          The base64Img size is 600x600.
          */
        this.setState({message: livenessId})
      },

      // Optional, but recommended
      /*
      The error types please refer to the README, and the corresponding error messages are in the language file of the `Resource/AAILanguageString.bundle/id.lproj/Localizable.strings` (depending on the language used by the phone)

      In fact, for the type of error this function gets, you don't need to pay attention to it, just prompt the error message and let the user retry.
      */
      onDetectionFailed: (errorCode, errorMessage, additionalInfo) => {
        console.log(">>>>> onDetectionFailed:", errorCode, errorMessage, additionalInfo)
        this.setState({message: errorMessage})
      },
    }

    AAIIOSLivenessSDK.startLiveness(config, callbackMap)
  }

  render() {
    return <View style={styles.container}>
              <Text style={styles.instructions}>STATUS: {this.state.message}</Text>
              <Text style={styles.instructions}>SDK Version: {this.state.version}</Text>
              <Button
                onPress={()=> {
                  this.sdkDemo()
                }}
                title="show liveness view"
                color="#841584"
              />
      </View>

  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  sdkContent: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  }
});
