package com.kdanmobile.kdan_others_library_for_android.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.kdanmobile.kdan_others_library_for_android.R;


public class SimpleWebViewActivity extends AppCompatActivity {
    public final static String INTENT_EXTRA_URL = "my_url_to_webview";
    private WebView mWebView;
    private ProgressBar mProgressBar;
    private String url;

    private TextView titleTextView;
    private TextView urlTextView;

    public static void launch(Context context, String url) {
        Intent intent = new Intent(context, SimpleWebViewActivity.class);
        intent.putExtra(SimpleWebViewActivity.INTENT_EXTRA_URL, url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simplewebview_layout);
        titleTextView = (TextView) findViewById(R.id.textView_simple_web_view_title);
        urlTextView = (TextView) findViewById(R.id.textView_simple_web_view_url);
        findViewById(R.id.button_simple_web_view_close).setOnClickListener(v -> onClickCloseBtn());
        findViewById(R.id.button_simple_web_view_open_in_browser).setOnClickListener(v -> onClickOpenInBrowserBtn());

        initWebView();
        initProgressBar();

        Intent intent = getIntent();
        if(intent != null) {
            processIntent(intent);
        }
    }

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

    }

    @Override
    public void onBackPressed() {
        if(mWebView != null && mWebView.canGoBack()){
            mWebView.goBack();
            return;
        }
        super.onBackPressed();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        mWebView = (WebView) findViewById(R.id.simple_webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.requestFocus();
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    private void initProgressBar() {
        mProgressBar = (ProgressBar) findViewById(R.id.webview_progressbar);
        mProgressBar.setProgress(0);
        mProgressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mWebView != null) mWebView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebView != null) mWebView.onPause();
    }

    private void processIntent(Intent intent) {
        url = intent.getStringExtra(INTENT_EXTRA_URL);
        if (url != null && mWebView != null) {
            mWebView.loadUrl(url);
            urlTextView.setText(url);
        }
    }

    protected void onClickCloseBtn() {
        finish();
    }

    protected void onClickOpenInBrowserBtn() {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }
    }

    protected void setToolbarBgColorRes(@ColorRes int colorRes) {
        int color = getResources().getColor(colorRes);
        setToolbarBgColor(color);
    }

    protected void setToolbarBgColor(@ColorInt int color) {
        findViewById(R.id.toolbar_simple_web_view).setBackgroundColor(color);
    }

    protected void setUrlTextColorRes(@ColorRes int colorRes) {
        int color = getResources().getColor(colorRes);
        setUrlTextColor(color);
    }

    protected void setUrlTextColor(@ColorInt int color) {
        ((TextView) findViewById(R.id.textView_simple_web_view_url)).setTextColor(color);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getScheme().equals("market")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    Activity host = (Activity) view.getContext();
                    host.startActivity(intent);
                    return true;
                } catch (ActivityNotFoundException e) {
                    // Google Play app is not installed, you may want to open the app store link
                    Uri uri = Uri.parse(url);
                    String webLink = "http://play.google.com/store/apps/" + uri.getHost() + "?" + uri.getQuery();
                    view.loadUrl(webLink);
                    return false;
                }
            }
            return false;
        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            titleTextView.setText(title);
        }

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if(mProgressBar != null){
                if (progress >= 100) {
                    mProgressBar.setProgress(0);
                } else {
                    mProgressBar.setProgress(progress);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
            mWebView = null;
        }
    }
}

