package com.datarecovery.master.module.customerservice;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.atmob.app.lib.base.BaseActivity;
import com.datarecovery.master.databinding.ActivityCustomerServiceBinding;
import com.datarecovery.master.utils.ActivityForResultUtil;
import com.datarecovery.master.utils.AndroidBug5497Workaround;
import com.gyf.immersionbar.ImmersionBar;
import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class CustomerServiceActivity extends BaseActivity<ActivityCustomerServiceBinding> {


    private static final String KEY_URL = "key_browser_url";
    private CustomerServiceViewModel customerServiceViewModel;

    //5.0以下使用
    private ValueCallback<Uri> uploadMessage;
    // 5.0及以上使用
    private ValueCallback<Uri[]> uploadMessageAboveL;

    public static void start(Context context, String url) {
        Intent intent = new Intent(context, CustomerServiceActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(KEY_URL, url);
        context.startActivity(intent);
    }


    @Override
    protected void configImmersion(@NonNull ImmersionBar immersionBar) {
        immersionBar.statusBarDarkFont(true);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initObserver();
        checkIntent(getIntent());
        AndroidBug5497Workaround.assistActivity(this);
    }


    @Override
    protected boolean shouldImmersion() {
        return true;
    }

    @Override
    protected void initViewModel() {
        customerServiceViewModel = getViewModelProvider().get(CustomerServiceViewModel.class);
        binding.setCustomerViewModel(customerServiceViewModel);
    }

    private void initView() {
        addTopStatusBarHeight(binding.browserHeader);
        initWebView();
    }

    private void initObserver() {
        customerServiceViewModel.getOnFinishEvent().observe(this, o -> onBackPressed());
    }


    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = binding.browserWebView.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        settings.setLoadsImagesAutomatically(true);
        settings.setMediaPlaybackRequiresUserGesture(true);
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        settings.setAllowFileAccess(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        binding.browserWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                if (url.startsWith("http://") || url.startsWith("https://")) {
                    binding.browserWebView.loadUrl(url);
                    return false;
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    return true;
                }
            }

        });
        binding.browserWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                customerServiceViewModel.setWebTitle(title);
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity("image/*,video/*");
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity(acceptType);
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity(acceptType);
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity(String.join(",", fileChooserParams.getAcceptTypes()));
                return true;
            }

        });
    }


    private void onActivityResultAboveL(int resultCode, Intent intent) {
        if (uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }


    private void openImageChooserActivity(String type) {
//        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("image/*");
        Intent gallery = new Intent(Intent.ACTION_PICK);
        gallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, type);
        new ActivityForResultUtil<Intent, ActivityResult>().startActivityForResult(this, new ActivityResultContracts.StartActivityForResult(), gallery, result -> {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri uriList = result.getData() == null || result.getResultCode() != RESULT_OK ? null : result.getData().getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(result.getResultCode(), result.getData());
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(uriList);
                uploadMessage = null;
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void checkIntent(Intent intent) {
        String url = intent.getStringExtra(KEY_URL);
        if (TextUtils.isEmpty(url)) {
            return;
        }
        if (isUrl(url)) {
            binding.browserWebView.loadUrl(url);
        } else {
            try {
                Uri uri = Uri.parse(url);
                startActivity(new Intent(Intent.ACTION_VIEW, uri));
            } catch (Exception e) {
                e.printStackTrace();
            }
            finish();
        }
    }

    public boolean isUrl(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        String upperCaseStr = str.toUpperCase();
        return upperCaseStr.startsWith("HTTP://") || upperCaseStr.startsWith("HTTPS://");
    }
}
