package com.wb.testcloud;

import android.annotation.TargetApi;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;


public class H5FaceWebChromeClient extends WebChromeClient {
    private static final String TAG = "H5FaceWebChromeClient";
    private MainActivity activity;
    private PermissionRequest request;
    private WebView webView;

    private ValueCallback<Uri> uploadMsg;
    private String acceptType;
    private ValueCallback<Uri[]> filePathCallback;
    private FileChooserParams fileChooserParams;

    public H5FaceWebChromeClient(MainActivity mActivity) {
        this.activity = mActivity;
    }

    @Override
    public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
        return super.onJsPrompt(view, url, message, defaultValue, result);
    }

    @Override
    public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
        result.confirm();
        return true;
    }


    /**
     * H5_TRTC 刷脸配置，这里负责处理来自H5页面发出的相机权限申请：先申请终端的相机权限，再授权h5请求
     * 按 resources 动态映射系统权限，所有分支必 grant 或 deny，避免 H5 端 getUserMedia 卡死。
     * @param request 来自H5页面的权限请求
     */
    @Override
    public void onPermissionRequest(PermissionRequest request) {
        if (request == null) return;
        final PermissionRequest req = request;
        String origin = req.getOrigin() != null ? req.getOrigin().toString() : "null";
        Log.d(TAG, "onPermissionRequest origin=" + origin);

        if (activity == null) {
            Log.d(TAG, "onPermissionRequest activity==null -> deny");
            req.deny();
            return;
        }

        // 按 H5 请求的资源动态映射系统权限，不申请多余权限。
        java.util.List<String> needPerms = new java.util.ArrayList<>();
        if (req.getResources() != null) {
            for (String res : req.getResources()) {
                if (PermissionRequest.RESOURCE_VIDEO_CAPTURE.equals(res)) {
                    needPerms.add(android.Manifest.permission.CAMERA);
                } else if (PermissionRequest.RESOURCE_AUDIO_CAPTURE.equals(res)) {
                    needPerms.add(android.Manifest.permission.RECORD_AUDIO);
                }
            }
        }
        if (needPerms.isEmpty()) {
            Log.d(TAG, "onPermissionRequest 无可映射权限 -> deny");
            req.deny();
            return;
        }

        if (activity.checkPermissionsGranted(needPerms)) {
            Log.d(TAG, "onPermissionRequest 权限已有，直接 grant");
            req.grant(req.getResources());
        } else {
            this.request = req;
            Log.d(TAG, "onPermissionRequest 权限缺失，异步申请 " + needPerms);
            activity.requestFacePermissions(needPerms.toArray(new String[0]));
        }
    }

    /** 异步权限申请失败时调用，deny 当前 pending 的 PermissionRequest，避免 H5 端 getUserMedia 卡死。 */
    public void denyPermissionRequest() {
        if (request != null) {
            Log.d(TAG, "denyPermissionRequest -> deny");
            request.deny();
            request = null;
        }
    }

    /**
     * 异步权限申请成功后，grant 当前 pending 的 PermissionRequest。
     */
    public void enterTrtcFaceVerify(){
        Log.d(TAG,"enterTrtcFaceVerify");
        if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){ // android sdk 21以上
            if (request != null) {
                Log.d(TAG, "enterTrtcFaceVerify grant");
                request.grant(request.getResources());
                this.request = null; // grant 后置空，避免残留已消费的 request 对象
            } else {
                Log.d(TAG, "enterTrtcFaceVerify request==null，无待授权请求");
            }
        }
    }


    // For Android >= 4.1  老的录制模式中，收到h5页面发送的录制请求
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
        Log.d(TAG,"openFileChooser-------acceptType="+acceptType);
        if (WBH5FaceVerifySDK.getInstance().isTencentH5FaceVerify(null,null,acceptType)){ //true 说明是腾讯的h5刷脸页面
            this.uploadMsg=uploadMsg;
            this.acceptType=acceptType;
            WBH5FaceVerifySDK.getInstance().setmUploadMessage(uploadMsg);
            if (activity!=null){ //申请系统的相机、录制、sd卡等权限
                activity.requestCameraPermission(false,true);
            }
        }

    }

    // For Lollipop 5.0+ Devices  老的录制模式中，收到h5页面发送的录制请求
    @TargetApi(21)
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
        if (fileChooserParams!=null&&fileChooserParams.getAcceptTypes()!=null&&fileChooserParams.getAcceptTypes().length>0){
            Log.d(TAG,"onShowFileChooser-------acceptType="+fileChooserParams.getAcceptTypes()[0]);
        }else {
            Log.d(TAG,"onShowFileChooser-------acceptType=null");
        }
        if (WBH5FaceVerifySDK.getInstance().isTencentH5FaceVerify(webView,fileChooserParams,null)){ //true说 明是腾讯的h5刷脸页面
            this.webView=webView;
            this.filePathCallback=filePathCallback;
            this.fileChooserParams=fileChooserParams;
            WBH5FaceVerifySDK.getInstance().setmUploadCallbackAboveL(filePathCallback);
            if (activity!=null){ //申请系统的相机、录制、sd卡等权限
                activity.requestCameraPermission(false,false);
            }
        }
        return true;

    }

    //老的录制模式中，拉起系统相机进行录制视频
    public boolean enterOldModeFaceVerify(boolean belowApi21){
        Log.d(TAG,"enterOldFaceVerify");
        if (belowApi21){ // For Android < 5.0
            if (WBH5FaceVerifySDK.getInstance().recordVideoForApiBelow21(uploadMsg, acceptType, activity)) { //腾讯的h5刷脸
                return true;
            }else {
                // todo 合作方如果其他的h5页面处理，则再次补充其他页面逻辑
            }
        }else { // For Android >= 5.0
            if (WBH5FaceVerifySDK.getInstance().recordVideoForApi21(webView, filePathCallback, activity,fileChooserParams)) {  //腾讯的h5刷脸
                return true;
            }else {
                // todo 合作方如果其他的h5页面处理，则再次补充其他页面逻辑

            }
        }
        return false;
    }


}
