package com.atmob.elec_asst.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.gyf.immersionbar.ImmersionBar;
import com.atmob.elec_asst.base.BaseActivity;
import com.atmob.elec_asst.databinding.ActivityBrowserBinding;


public class BrowserActivity extends BaseActivity<ActivityBrowserBinding> {

    private static final String KEY_URL = "key_browser_url";

    public static void start(Context context, String url) {
        Intent intent = new Intent(context, BrowserActivity.class);
        intent.putExtra(KEY_URL, url);
        context.startActivity(intent);
    }


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



    private void initView() {
        addTopStatusBarHeight(binding.browserHeader);
        initWebView();
        binding.browserHeader.setNavigationOnClickListener(view -> {
            finish();
        });
    }


    @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 {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        return true;
                    } catch (Exception e) {
                        return false;
                    }
                }
            }
        });
        binding.browserWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                binding.browserHeader.setTitle(title);
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        checkIntent(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://");
    }


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

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

}
