package com.steps.tmuapp;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import androidx.appcompat.app.AlertDialog;

import com.steps.tmuapp.lib.Permissions;

import java.net.URISyntaxException;
import java.security.acl.Permission;

class MyWebViewClient extends WebViewClient {
    private Activity mActivity;
    private final ProgressBar mProgressBar;
    private final androidx.appcompat.app.ActionBar mActionBar;
    private static final String TAG = "=MyWebViewClient=";
    private WebView mView;
    Boolean shouldClearHistory = false;

//    public MyWebViewClient(ProgressBar progressBar, ActionBar actionBar) {
//        this.mProgressBar=progressBar;
//        mActionBar =actionBar;
//        clearHistory = true;
//    }

    public MyWebViewClient(Activity activity, androidx.appcompat.app.ActionBar actionBar) {
        mActivity = activity;
        this.mProgressBar = activity.findViewById(R.id.progressBar);
//        TextView mToolbarTitle = activity.findViewById(R.id.toolbar_title);
//        ImageView mToolBarLogo = activity.findViewById(R.id.toolbar_logo);
        mActionBar = actionBar;
//        shouldClearHistory = true;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        mProgressBar.setVisibility(View.VISIBLE);
        String url = request.getUrl().toString();
        Log.i(TAG, "shouldOverrideUrlLoading :" + url);
        view.loadUrl("https://docs.google.com/gview?embedded=true&url=" + url);
        if (url.startsWith("tel:") ) {
            checkPermissionAndDial(url);
            view.stopLoading();
            mProgressBar.setVisibility(View.GONE);
            return true;
        }else if (request.getUrl().getScheme().contains("intent")){
            //for Line share
            Intent iuri = null;
            try {
                iuri = Intent.parseUri(url, 0);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            mActivity.startActivity(iuri);
            view.stopLoading();
            return true;
        }else if (url.startsWith("line://") ) {
            view.stopLoading();
            mProgressBar.setVisibility(View.GONE);
            startLinePayApp(url);
            return true;
        }
        view.loadUrl(request.getUrl().toString());
        return super.shouldOverrideUrlLoading(view, request);
    }


    private void startLinePayApp(String paymentUrl){
        int linePaySupportedVersion = 230;
        Context context = mActivity;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo("jp.naver.line.android", 0);
            int versionCode = packageInfo.versionCode;
            if (linePaySupportedVersion <= versionCode) {
                launchUri(paymentUrl);
            } else {
                confirmLineInstall(context);
            }
        } catch (PackageManager.NameNotFoundException e) {
            confirmLineInstall(context);
        }
    }

    private void confirmLineInstall(Context context) {
        new AlertDialog.Builder(context)
                .setTitle("LINE Pay")
                .setMessage(mActivity.getString(R.string.linepay_confirm))
                .setCancelable(false)
                .setPositiveButton(mActivity.getString(R.string.linepay_install), new
                        DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                launchUri("market://details?id=jp.naver.line.android");
                            }
                        })
                .setNegativeButton(mActivity.getString(R.string.linepay_cancel), new
                        DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                .show();
    }
    private void launchUri(String uriString) {
//        if (BuildConfig.DEBUG) uriString = uriString.replace("linesandbox", "line");
        Uri uri = Uri.parse(uriString);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        mActivity.startActivity(intent);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        //注入Javascript 設定App版號
        // appVersion 1.1 (含)以上支援 Phone call
        String javascript = "javascript: var appVersion = 1.1;";
//        view.loadUrl(javascript);
        view.evaluateJavascript(javascript, null);
//        String cookies = CookieManager.getInstance().getCookie(url);
        //        Log.d(TAG, "All the cookies in a string:" + cookies);
        mProgressBar.setVisibility(View.GONE);
        //處理Back按鈕
        if (shouldClearHistory) view.clearHistory();
        shouldClearHistory = false;
        if(view.canGoBackOrForward(-1)){
            mActionBar.setDisplayHomeAsUpEnabled(true);
        }
        else{
//            mToolbarTitle.setVisibility(View.GONE);
//            mToolBarLogo.setVisibility(View.VISIBLE);
            mActionBar.setDisplayHomeAsUpEnabled(false);
        }

    }


    /**
     * Report an error to the host application.
     *
     * This method was deprecated in API level 23 (Marshmallow, Android 6.0)
     *
     * @param view The WebView that is initiating the callback
     * @param errorCode The error code corresponding to an ERROR_* value
     * @param description A String describing the error
     * @param failingUrl The url that failed to load
     */
    @Override
    public void onReceivedError(WebView view,
                                int errorCode,
                                String description,
                                final String failingUrl) {
        Log.d(TAG, "onReceivedError() (old)");
        final LinearLayout errorPage = mActivity.findViewById(R.id.network_error_view);
        Button retryButton = errorPage.findViewById(R.id.error_button_retry);
        retryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                errorPage.setVisibility(View.GONE);
                mView.loadUrl(failingUrl);
                mProgressBar.setVisibility(View.VISIBLE);
            }
        });
        errorPage.setVisibility(View.VISIBLE);
    }

    /**
     * Report web resource loading error to the host application.
     *
     * @param view The WebView that is initiating the callback
     * @param request The originating request
     * @param error Information about the error occurred
     */
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onReceivedError(WebView view,
                                final WebResourceRequest request,
                                WebResourceError error) {
        final WebView mView = view;
        Log.d(TAG, "onReceivedError()");
        mView.loadUrl("about:blank");
        if (request.isForMainFrame()) {
            final LinearLayout errorPage = mActivity.findViewById(R.id.network_error_view);
            final Button retryButton = errorPage.findViewById(R.id.error_button_retry);
            retryButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    errorPage.setVisibility(View.GONE);
                    mView.loadUrl(request.getUrl().toString());
                }
            });
            errorPage.setVisibility(View.VISIBLE);
        }
    }

    /**
     * Checks the permission and dials the phone number.
     *
     * @param telUrl the tel: phone number URL.
     */
    private void checkPermissionAndDial(String telUrl) {
        // M is for Marshmallow! - API Level 23 (Android 6.0)
        // Before Marshmallow, all permissions are granted at the apk installation.
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            dialPhoneNumber(telUrl);
            return;
        }

        // Since Marshmallow, an application needs to ask for the permissions after installation.
        boolean isPermitted = true;
        for (String permission : Permissions.PHONE_PERMISSIONS) {
            isPermitted = isPermitted &&
                    (mActivity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
        }
        if (isPermitted) {
            dialPhoneNumber(telUrl);
            return;
        }
        Log.d(TAG, "Phone Permission: Asking ...");
        ((MainActivity) mActivity).telUrl = telUrl;
        mActivity.requestPermissions(Permissions.PHONE_PERMISSIONS, Permissions.REQUEST_PHONE_PERMISSION);
    }

    /**
     * Dials the phone number.
     *
     * @param telUrl the tel: phone number URL
     */
    private void dialPhoneNumber(String telUrl) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse(telUrl);
        intent.setData(data);
        mActivity.startActivity(intent);
    }

//    @Override
//    public void onReceivedError(WebView view, final WebResourceRequest request, WebResourceError error) {
//        final WebView mView = view;
//        Log.d(TAG, "onReceivedError() (old)");
//        final LinearLayout errorPage =mActivity.findViewById(R.id.network_error_view);
//        Button retryButton = mActivity.findViewById(R.id.error_button_retry);
//        retryButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                errorPage.setVisibility(View.GONE);
//                mView.loadUrl(request.getUrl().toString());
//            }
//        });
//        errorPage.setVisibility(View.VISIBLE);
//    }
}
