package com.oliveapp.liveness.sample.liveness.view_controller;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;

import com.oliveapp.face.livenessdetectorsdk.livenessdetector.datatype.LivenessDetectionFrames;
import com.oliveapp.face.livenessdetectorsdk.livenessdetector.datatype.OliveappFaceInfo;
import com.oliveapp.liveness.sample.R;

import java.util.ArrayList;

/**
 * Created by SiKang on 2019-08-12.
 */
public class LivenessDetectionActivity extends LivenessDetectionMainActivity {
    private static final String SP_NAME = "yitu_liveness";
    private static final String FACE_DATA = "face_data";

    SharedPreferences.Editor spEditor;

    @Override
    public void onLivenessSuccess(OliveappFaceInfo oliveappFaceInfo) {
        LivenessDetectionFrames pkg = this.getLivenessDetectionPackage();
        if ((pkg != null ? pkg.verificationData : null) == null) {
            finishForResult(false, getResources().getString(R.string.faceid_detect_fail));
        } else {
            if (pkg.verificationData != null) {
                spEditor.putString(FACE_DATA, Base64.encodeToString(pkg.verificationData, Base64.NO_WRAP));
            } else {
                spEditor.putString(FACE_DATA, "");
            }
            spEditor.commit();
            finishForResult(true, "");
        }
    }

    public static String getFaceData(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SP_NAME, Activity.MODE_PRIVATE);
        return preferences.getString(FACE_DATA, "");
    }


    public static final String FAILED_MSG = "failed_msg";


    /**
     * 初始化活体检测
     */
    @Override
    public void onInitializeSucc() {
        super.onInitializeSucc();
        super.startVerification();
        spEditor = getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit();
    }

    @Override
    public void onInitializeFail(Throwable e) {
        super.onInitializeFail(e);
        finishForResult(false, getResources().getString(R.string.initialize_fail));
    }

    /**
     * 活体检测结果回调
     */
    @Override
    public void onLivenessSuccess(LivenessDetectionFrames livenessDetectionFrames, OliveappFaceInfo faceInfo) {
        super.onLivenessSuccess(livenessDetectionFrames, faceInfo);
        if (livenessDetectionFrames == null || livenessDetectionFrames.verificationData == null) {
            finishForResult(false, getResources().getString(R.string.faceid_detect_fail));
        } else {
            if (livenessDetectionFrames.verificationData != null) {
                spEditor.putString(FACE_DATA, Base64.encodeToString(livenessDetectionFrames.verificationData, Base64.NO_WRAP));
            } else {
                spEditor.putString(FACE_DATA, "");
            }
            spEditor.commit();
            finishForResult(true, "");
        }
    }

    @Override
    public void onLivenessFail(int result, LivenessDetectionFrames livenessDetectionFrames) {
        super.onLivenessFail(result, livenessDetectionFrames);
        finishForResult(false, getResources().getString(R.string.faceid_detect_fail));
    }

    /**
     * 活体检测帧回调
     */
    @Override
    public void onFrameDetected(int currentActionType, int actionState, int sessionState, int remainingTimeoutMilliSecond, OliveappFaceInfo faceInfo, ArrayList<Integer> errorCodeOfInAction) {
        super.onFrameDetected(currentActionType, actionState, sessionState, remainingTimeoutMilliSecond, faceInfo, errorCodeOfInAction);
        if (remainingTimeoutMilliSecond / 1000 <= 0) { // 活体检测超时
            finishForResult(false, getResources().getString(R.string.faceid_detect_fail));

        }
    }

    /**
     * 返回结果
     */
    private void finishForResult(final boolean isLivenessSuccess, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isLivenessSuccess) {
                    setResult(Activity.RESULT_OK);
                    finish();
                } else {
                    if (!TextUtils.isEmpty(msg)) {
                        Intent intent = new Intent();
                        intent.putExtra(FAILED_MSG, msg);
                        setResult(Activity.RESULT_CANCELED, intent);
                    } else {
                        setResult(Activity.RESULT_CANCELED);
                    }
                    finish();
                }
            }
        });
    }
}
