package xyz.hermez.components;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.PermissionRequest;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.firebase.BuildConfig;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import xyz.hermez.MainActivity;
import xyz.hermez.R;
import xyz.hermez.Utils;

/* loaded from: classes.dex */
public class WebPageView extends WebView {
    public static final String EXTRA_FROM_NOTIFICATION = "EXTRA_FROM_NOTIFICATION";
    public static final int INPUT_FILE_REQUEST_CODE = 1;
    protected String ErrorAssetHTML;
    protected final String TAG;
    private MainActivity activity;
    protected String allowedDomain;
    protected boolean clearHistoryOnFinished;
    protected String failedURL;
    protected WebPageNativeAPI javascriptInterface;
    protected ProgressBar loaderMask;
    protected WebLoaderProgressHandler progressHandler;
    protected boolean swipeHandled;
    protected SwipeRefreshLayout swipeRefreshLayout;

    public WebPageView(Context context) {
        super(context);
        this.TAG = "app.webview";
        this.ErrorAssetHTML = "file:///android_asset/www/error.html";
        this.javascriptInterface = null;
        this.allowedDomain = BuildConfig.FLAVOR;
        this.swipeHandled = false;
        this.clearHistoryOnFinished = false;
        init();
    }

    public void setProgressHandler(WebLoaderProgressHandler webLoaderProgressHandler) {
        this.progressHandler = webLoaderProgressHandler;
    }

    public WebPageView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        this.TAG = "app.webview";
        this.ErrorAssetHTML = "file:///android_asset/www/error.html";
        this.javascriptInterface = null;
        this.allowedDomain = BuildConfig.FLAVOR;
        this.swipeHandled = false;
        this.clearHistoryOnFinished = false;
        Log.d("app.webview", "Created ");
        init();
    }

    public WebPageView(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
        this.TAG = "app.webview";
        this.ErrorAssetHTML = "file:///android_asset/www/error.html";
        this.javascriptInterface = null;
        this.allowedDomain = BuildConfig.FLAVOR;
        this.swipeHandled = false;
        this.clearHistoryOnFinished = false;
        init();
    }

    public void setActivity(MainActivity mainActivity) {
        this.activity = mainActivity;
    }

    protected void init() {
        CookieManager.getInstance().setAcceptCookie(true);
        setLayerType(2, null);
        Log.d("app.webview", "initialize webpage... ");
        setWebViewClient(new WebViewClient() { // from class: xyz.hermez.components.WebPageView.1
            @Override // android.webkit.WebViewClient
            public boolean shouldOverrideUrlLoading(WebView webView, String str) {
                if (str.startsWith("tel:")) {
                    WebPageView.this.getContext().startActivity(new Intent("android.intent.action.DIAL", Uri.parse(str)));
                    return true;
                }
                if (!str.toLowerCase().trim().startsWith("http")) {
                    WebPageView.this.getContext().startActivity(new Intent("android.intent.action.VIEW", Uri.parse(str)));
                    return true;
                }
                WebPageView.this.setLoaderVisibility(true);
                webView.loadUrl(str);
                return false;
            }

            @Override // android.webkit.WebViewClient
            public void onPageStarted(WebView webView, String str, Bitmap bitmap) {
                if (WebPageView.this.javascriptInterface != null) {
                    WebPageView.this.javascriptInterface.js_consumeBackKey("no");
                }
                WebPageView.this.setLoaderVisibility(true);
            }

            @Override // android.webkit.WebViewClient
            public void onPageFinished(WebView webView, String str) {
                WebPageView.this.setLoaderVisibility(false);
                if (WebPageView.this.clearHistoryOnFinished) {
                    Log.d("WebPageView", "clear history after finished loading: " + str);
                    webView.clearHistory();
                }
                WebPageView.this.clearHistoryOnFinished = false;
                try {
                    CookieManager.getInstance().flush();
                } catch (Exception e) {
                    Log.e("app.webview", "error flushing cookie", e);
                }
                Log.d("app.webview", str + " -> " + CookieManager.getInstance().getCookie(str));
            }

            @Override // android.webkit.WebViewClient
            public void onReceivedError(WebView webView, int i, String str, String str2) {
                if (str2 == null || !str2.contains("hermez.")) {
                    Log.e("app.webview", "Ignore webview error on " + str2 + ": " + str);
                    return;
                }
                Log.e("app.webview", "WEBVIEW ERROR: " + str2);
                try {
                    webView.stopLoading();
                } catch (Exception unused) {
                }
                try {
                    webView.clearView();
                } catch (Exception unused2) {
                }
                if (str2.toLowerCase().startsWith("http")) {
                    Log.e("app.webview", "ReceivedError on WebView. ERROR CODE is " + i);
                    Log.e("app.webview", "description is " + str);
                    Log.e("app.webview", "failingUrl is " + str2);
                    try {
                        webView.loadUrl(WebPageView.this.ErrorAssetHTML + "?errorCode=" + i + "&errorDescription=" + str);
                        WebPageView.this.failedURL = str2;
                    } catch (Exception e) {
                        Log.e("error", e.toString());
                    }
                }
            }

            @Override // android.webkit.WebViewClient
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                String uri = webResourceRequest.getUrl().toString();
                int errorCode = webResourceError.getErrorCode();
                String str = (String) webResourceError.getDescription();
                if (!webResourceRequest.isForMainFrame()) {
                    super.onReceivedError(webView, webResourceRequest, webResourceError);
                } else {
                    onReceivedError(webView, errorCode, str, uri);
                }
            }

            @Override // android.webkit.WebViewClient
            public void onReceivedHttpError(WebView webView, WebResourceRequest webResourceRequest, WebResourceResponse webResourceResponse) {
                String uri = webResourceRequest.getUrl().toString();
                int statusCode = webResourceResponse.getStatusCode();
                String str = "HTTP Error: " + statusCode;
                Log.d("app.webview", str + " " + uri);
                if (!webResourceRequest.isForMainFrame()) {
                    super.onReceivedHttpError(webView, webResourceRequest, webResourceResponse);
                } else {
                    onReceivedError(webView, statusCode, str, uri);
                }
            }

            @Override // android.webkit.WebViewClient
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                Log.d("app.webview", "SSL Error: " + sslError.toString());
                sslErrorHandler.proceed();
            }
        });
        setWebChromeClient(new WebChromeClient() { // from class: xyz.hermez.components.WebPageView.2
            @Override // android.webkit.WebChromeClient
            public void onPermissionRequest(PermissionRequest permissionRequest) {
                Log.d("app.webview", "onPermissionRequest");
                if (Build.VERSION.SDK_INT >= 21) {
                    permissionRequest.grant(permissionRequest.getResources());
                }
            }

            @Override // android.webkit.WebChromeClient
            public void onGeolocationPermissionsShowPrompt(String str, GeolocationPermissions.Callback callback) {
                callback.invoke(str, false, false);
            }

            @Override // android.webkit.WebChromeClient
            public void onProgressChanged(WebView webView, int i) {
                if (WebPageView.this.progressHandler != null) {
                    WebPageView.this.progressHandler.onWebviewProgressChanged(webView, i);
                } else {
                    super.onProgressChanged(webView, i);
                }
            }

            @Override // android.webkit.WebChromeClient
            public boolean onJsAlert(WebView webView, String str, String str2, JsResult jsResult) {
                new AlertDialog.Builder(webView.getContext()).setTitle(webView.getContext().getString(R.string.app_name)).setMessage(str2).setPositiveButton(webView.getContext().getString(android.R.string.ok), new DialogInterface.OnClickListener() { // from class: xyz.hermez.components.WebPageView.2.1
                    @Override // android.content.DialogInterface.OnClickListener
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).create().show();
                jsResult.confirm();
                return true;
            }

            @Override // android.webkit.WebChromeClient
            public boolean onJsConfirm(WebView webView, String str, String str2, final JsResult jsResult) {
                new AlertDialog.Builder(webView.getContext()).setTitle(webView.getContext().getString(R.string.app_name)).setMessage(str2).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { // from class: xyz.hermez.components.WebPageView.2.3
                    @Override // android.content.DialogInterface.OnClickListener
                    public void onClick(DialogInterface dialogInterface, int i) {
                        jsResult.confirm();
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { // from class: xyz.hermez.components.WebPageView.2.2
                    @Override // android.content.DialogInterface.OnClickListener
                    public void onClick(DialogInterface dialogInterface, int i) {
                        jsResult.cancel();
                    }
                }).create().show();
                return true;
            }

            /* JADX WARN: Removed duplicated region for block: B:12:0x00ec  */
            /* JADX WARN: Removed duplicated region for block: B:16:0x00cc  */
            /* JADX WARN: Removed duplicated region for block: B:23:0x0054  */
            /* JADX WARN: Removed duplicated region for block: B:9:0x00c7  */
            @Override // android.webkit.WebChromeClient
            /*
                Code decompiled incorrectly, please refer to instructions dump.
            */
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                File file;
                Intent intent = null;
                if (WebPageView.this.activity.mFilePathCallback != null) {
                    WebPageView.this.activity.mFilePathCallback.onReceiveValue(null);
                }
                WebPageView.this.activity.mFilePathCallback = valueCallback;
                Intent intent2 = new Intent("android.media.action.IMAGE_CAPTURE");
                if (intent2.resolveActivity(WebPageView.this.getContext().getPackageManager()) != null) {
                    try {
                        file = WebPageView.createImageFile();
                    } catch (IOException e) {
                        e = e;
                        file = null;
                    }
                    try {
                        intent2.putExtra("PhotoPath", WebPageView.this.activity.mCameraPhotoPath);
                    } catch (IOException e2) {
                        e = e2;
                        Log.e("app.webview", "Unable to create Image File", e);
                        if (file != null) {
                        }
                        Intent intent3 = new Intent("android.intent.action.GET_CONTENT");
                        intent3.addCategory("android.intent.category.OPENABLE");
                        intent3.setType("image/*");
                        if (intent != null) {
                        }
                        Intent intent4 = new Intent("android.intent.action.CHOOSER");
                        intent4.putExtra("android.intent.extra.INTENT", intent3);
                        intent4.putExtra("android.intent.extra.TITLE", "Image Chooser");
                        intent4.putExtra("android.intent.extra.INITIAL_INTENTS", r1);
                        if (Build.VERSION.SDK_INT >= 21) {
                        }
                        WebPageView.this.activity.startActivityForResult(intent4, 1);
                        return true;
                    }
                    if (file != null) {
                        WebPageView.this.activity.mCameraPhotoPath = "file:" + file.getAbsolutePath();
                        Uri uriForFile = FileProvider.getUriForFile(WebPageView.this.activity, "xyz.hermez.provider", file);
                        intent2.putExtra("output", uriForFile);
                        Iterator<ResolveInfo> it = WebPageView.this.activity.getPackageManager().queryIntentActivities(intent2, 65536).iterator();
                        while (it.hasNext()) {
                            WebPageView.this.activity.grantUriPermission(it.next().activityInfo.packageName, uriForFile, 3);
                        }
                    }
                    Intent intent32 = new Intent("android.intent.action.GET_CONTENT");
                    intent32.addCategory("android.intent.category.OPENABLE");
                    intent32.setType("image/*");
                    Intent[] intentArr = intent != null ? new Intent[]{intent} : new Intent[0];
                    Intent intent42 = new Intent("android.intent.action.CHOOSER");
                    intent42.putExtra("android.intent.extra.INTENT", intent32);
                    intent42.putExtra("android.intent.extra.TITLE", "Image Chooser");
                    intent42.putExtra("android.intent.extra.INITIAL_INTENTS", intentArr);
                    if (Build.VERSION.SDK_INT >= 21) {
                        intent42.addFlags(2);
                    }
                    WebPageView.this.activity.startActivityForResult(intent42, 1);
                    return true;
                }
                intent = intent2;
                Intent intent322 = new Intent("android.intent.action.GET_CONTENT");
                intent322.addCategory("android.intent.category.OPENABLE");
                intent322.setType("image/*");
                if (intent != null) {
                }
                Intent intent422 = new Intent("android.intent.action.CHOOSER");
                intent422.putExtra("android.intent.extra.INTENT", intent322);
                intent422.putExtra("android.intent.extra.TITLE", "Image Chooser");
                intent422.putExtra("android.intent.extra.INITIAL_INTENTS", intentArr);
                if (Build.VERSION.SDK_INT >= 21) {
                }
                WebPageView.this.activity.startActivityForResult(intent422, 1);
                return true;
            }
        });
        setInitialScale(0);
        WebSettings settings = getSettings();
        settings.setUserAgentString(Utils.HttpUserAgent(getContext(), settings.getUserAgentString()));
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setDisplayZoomControls(false);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setGeolocationEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setCacheMode(2);
        settings.setMixedContentMode(2);
        setScrollBarStyle(33554432);
        setScrollbarFadingEnabled(true);
        requestFocus(130);
        setFocusable(true);
        setFocusableInTouchMode(true);
        handleSwipeRefreshLayout();
    }

    @Override // android.webkit.WebView
    public void loadUrl(String str) {
        if (str.startsWith("http")) {
            Log.d("app.webview", "Loading " + str);
            super.loadUrl(str);
        } else {
            super.loadUrl(str);
        }
        requestFocus(130);
    }

    protected void findLoaderMask() {
        handleSwipeRefreshLayout();
        if (this.loaderMask == null) {
            try {
                this.loaderMask = (ProgressBar) ((ViewGroup) getParent().getParent()).findViewById(R.id.browser_loader_mask);
            } catch (Exception e) {
                this.loaderMask = null;
                e.printStackTrace();
            }
        }
    }

    public void setSwipeRefreshLayoutEnabled(boolean z) {
        SwipeRefreshLayout swipeRefreshLayout = this.swipeRefreshLayout;
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setEnabled(z);
        }
    }

    protected void handleSwipeRefreshLayout() {
        if (this.swipeHandled) {
            return;
        }
        try {
            SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) ((ViewGroup) getParent().getParent()).findViewById(R.id.swipeContainer);
            this.swipeRefreshLayout = swipeRefreshLayout;
            if (swipeRefreshLayout != null) {
                swipeRefreshLayout.setEnabled(false);
                this.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { // from class: xyz.hermez.components.WebPageView$$ExternalSyntheticLambda0
                    @Override // androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
                    public final void onRefresh() {
                        WebPageView.this.lambda$handleSwipeRefreshLayout$0$WebPageView();
                    }
                });
                this.swipeHandled = true;
            } else {
                Log.e("app.webview", "Cannot Find SwipeRefreshLayout: " + this.swipeRefreshLayout);
            }
        } catch (Exception e) {
            Log.e("app.webview", "Failed to initialize SwipeRefreshLayout: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public /* synthetic */ void lambda$handleSwipeRefreshLayout$0$WebPageView() {
        SwipeRefreshLayout swipeRefreshLayout = this.swipeRefreshLayout;
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
        reload();
    }

    public void setLoaderVisibility(boolean z) {
        findLoaderMask();
        if (this.loaderMask != null) {
            Log.e("app.webview", "setting loader mask visibility to: " + z);
            this.loaderMask.setVisibility(z ? 0 : 8);
            return;
        }
        Log.d("app.webview", "Cannot Find Loader Mask");
    }

    public void addJavascriptInterface(WebPageNativeAPI webPageNativeAPI, String str) {
        super.addJavascriptInterface((Object) webPageNativeAPI, str);
        this.javascriptInterface = webPageNativeAPI;
    }

    public boolean consumeBackKey() {
        WebPageNativeAPI webPageNativeAPI = this.javascriptInterface;
        if (webPageNativeAPI == null) {
            return false;
        }
        return webPageNativeAPI.consumeBackKey();
    }

    public void setClearHistoryOnFinished(boolean z) {
        this.clearHistoryOnFinished = z;
    }

    @Override // android.webkit.WebView
    public void reload() {
        String str = this.failedURL;
        if (str != null && !str.isEmpty()) {
            loadUrl(this.failedURL);
            this.failedURL = null;
        } else {
            super.reload();
        }
    }

    public static File createImageFile() throws IOException {
        return File.createTempFile("JPEG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + "_", ".jpg", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
    }
}
