package com.datarecovery.master.module.browser;

import android.annotation.SuppressLint;
import android.app.Activity;
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.atmob.app.lib.base.BaseActivity;
import com.datarecovery.master.databinding.ActivityBrowserBinding;
import com.gyf.immersionbar.ImmersionBar;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class BrowserActivity extends BaseActivity<ActivityBrowserBinding> {

    private static final String KEY_URL = "key_browser_url";
    private BrowserViewModel browserViewModel;

    public static void start(Context context, String url) {
        Intent intent = new Intent(context, BrowserActivity.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());
    }

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

    @Override
    protected void initViewModel() {
        browserViewModel = getViewModelProvider().get(BrowserViewModel.class);
        binding.setBrowserViewModel(browserViewModel);
    }

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

    private void initObserver() {
        browserViewModel.getOnFinishEvent().observe(this, o -> 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 {
                    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);
                browserViewModel.setWebTitle(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://");
    }

}
