package epson.print;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;

import com.box.androidsdk.content.models.BoxFile;
import com.box.androidsdk.content.requests.BoxRequestsMetadata;
import com.epson.iprint.prtlogger.Analytics;
import com.epson.iprint.prtlogger.NewLoggerController;
import com.epson.iprint.prtlogger.PrintLog;
import com.epson.iprint.shared.EpsoniPrintSharedActivity;
import com.epson.mobilephone.common.license.LicenseTopActivity;
import com.epson.mobilephone.common.wifidirect.NfcTagUtils;
import com.epson.mobilephone.common.wifidirect.WiFiDirectManager;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import epson.common.ExternalFileUtils;
import epson.common.IprintLicenseInfo;
import epson.common.IprintUserSurveyInfo;
import epson.common.Utils;
import epson.print.Util.CommonMessage;
import epson.print.Util.EPLog;

public class WebviewActivity extends ActivityIACommon implements CommonDefine, View.OnClickListener, View.OnKeyListener {
    private static final int ACTION_PRINT_WEB = 2;
    private static final float FIRST_SCREEN_SCALE_VALUE = 0.0f;
    private static final int MESSAGE_WAIT_WEBVIEW_PROGRESS = 3;
    private static final int Menu_Add_Bookmark = 4;
    private static final int Menu_Back = 1;
    private static final int Menu_Bookmark = 6;
    private static final int Menu_History = 5;
    private static final int Menu_Next = 2;
    private static final int Menu_Print = 7;
    public static final String PARAMS_KEY_WEBVIEW_PRINT_LOG = "print_log";
    private static final int REQUEST_CODE_LICENSE_CHECK = 3;
    protected static final String TAG = "WebviewActivity";
    private static final int WEBVIEW_MENU_GROUP = 0;
    private final int ERROR_CODE = 1;
    private final int SDCARD_ERROR = 2;
    private ImageButton btnClearUrl;
    private boolean captureStart = false;
    private boolean checkImage = false;
    private boolean checkSharepage = false;
    private int countUrl;
    private String inURL = null;
    boolean isBuy = false;
    private boolean isCustomAction = false;
    boolean isFaq = false;
    boolean isInfo = false;
    private ArrayList<String> mAddImageView = new ArrayList<>();
    private boolean mCanClear;
    private boolean mCanRefresh;
    private boolean mCanStop;
    private Dialog mCustomPro;
    public AlertDialog mErrorDialog;
    private Integer[] mImageArray = new Integer[2];
    private ImageCreateThread mImageCreateThread;
    private Intent mIntent;
    boolean mIsBookmark;
    boolean mIsBookmarkEmpty;
    private boolean mIsFinish;
    boolean mIsFistLoad;
    boolean mIsLoadError = false;
    private MenuItem[] mItem = new MenuItem[6];
    private int mLastHeight = 0;
    private ArrayList<HashMap<String, String>> mListUrl = new ArrayList<>();
    private LinearLayout mLoadWebLayout;
    private volatile boolean mPreviewWebInterrupted;
    private PrintLog mPrintLog;
    IprintStrictMode.StrictModeInterface mStrictMode = IprintStrictMode.getStrictMode();
    private WebViewClient mWebClient = new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView webView, String str) {
            return false;
        }

        public void onPageStarted(WebView webView, String str, Bitmap bitmap) {
            if (!checkSharepage) {
                mLoadWebLayout.setVisibility(View.VISIBLE);
            } else {
                showLoadingDialog();
            }
            WebviewActivity webviewActivity = WebviewActivity.this;
            setTextOnUrlEditText(fixUrl(str));
            boolean unused = mIsFinish = false;
            boolean unused2 = mCanStop = true;
            setClearButtonAppearance(0);
            boolean unused3 = mCanRefresh = false;
            invalidateOptionsMenu();
        }

        public void onPageFinished(WebView webView, String str) {
            boolean z;
            Map<String, ?> all;
            EPLog.d(TAG, "onPageFinished: " + str);
            boolean unused = mIsFinish = true;
            boolean unused2 = mCanRefresh = true;
            boolean unused3 = mCanStop = false;
            setClearButtonAppearance(1);
            if (!getTitle().toString().equals("Web page not available")) {
                String unused4 = strUrlIn = str;
                String unused5 = inURL = null;
                mIsLoadError = false;
            } else {
                mIsLoadError = true;
            }
            invalidateOptionsMenu();
            if (!isBuy && !isFaq && !isInfo) {
                mStrictMode.permitAll();
                WebviewActivity webviewActivity = WebviewActivity.this;
                SharedPreferences unused6 = statePre = getSharedPreferences("history", 0);
                if (mIsFistLoad || (all = statePre.getAll()) == null) {
                    z = false;
                } else {
                    mListUrl.clear();
                    for (String next : all.keySet()) {
                        HashMap hashMap = new HashMap();
                        hashMap.put("key", next);
                        hashMap.put(BoxRequestsMetadata.UpdateItemMetadata.BoxMetadataUpdateTask.VALUE, all.get(next).toString());
                        mListUrl.add(hashMap);
                    }
                    WebviewActivity webviewActivity2 = WebviewActivity.this;
                    int unused7 = webviewActivity2.countUrl = webviewActivity2.mListUrl.size();
                    z = false;
                    for (int i = 0; i < mListUrl.size(); i++) {
                        if (str.equalsIgnoreCase((String) ((HashMap) mListUrl.get(i)).get(BoxRequestsMetadata.UpdateItemMetadata.BoxMetadataUpdateTask.VALUE))) {
                            z = true;
                        }
                    }
                }
                if (!z || mIsFistLoad) {
                    HashMap hashMap2 = new HashMap();
                    access$1308(WebviewActivity.this);
                    WebviewActivity webviewActivity3 = WebviewActivity.this;
                    SharedPreferences.Editor unused8 = webviewActivity3.stateEditor = webviewActivity3.statePre.edit();
                    stateEditor.putString(String.valueOf(countUrl), str);
                    EPLog.i("Save countUrl " + countUrl + " : ", str);
                    stateEditor.commit();
                    hashMap2.put("key", String.valueOf(countUrl));
                    hashMap2.put(BoxRequestsMetadata.UpdateItemMetadata.BoxMetadataUpdateTask.VALUE, str);
                    mListUrl.add(hashMap2);
                    mIsFistLoad = false;
                    for (int i2 = 0; i2 < mListUrl.size(); i2++) {
                        EPLog.i(((String) ((HashMap) mListUrl.get(i2)).get("key")) + " : ", (String) ((HashMap) mListUrl.get(i2)).get(BoxRequestsMetadata.UpdateItemMetadata.BoxMetadataUpdateTask.VALUE));
                    }
                } else {
                    mIsFistLoad = false;
                    EPLog.i("Link: " + str, " already exist");
                }
                if (!str.startsWith("file://")) {
                    WebviewActivity webviewActivity4 = WebviewActivity.this;
                    SharedPreferences unused9 = webviewActivity4.statePre = webviewActivity4.getSharedPreferences(CommonDefine.SAVE_URL, 0);
                    WebviewActivity webviewActivity5 = WebviewActivity.this;
                    SharedPreferences.Editor unused10 = webviewActivity5.stateEditor = webviewActivity5.statePre.edit();
                    stateEditor.putString(CommonDefine.SAVE_URL, str);
                    stateEditor.commit();
                }
                mStrictMode.restoreStatus();
            }
            if (checkSharepage && !captureStart) {
                previewWeb();
            }
        }

        public void onReceivedError(WebView webView, int i, String str, String str2) {
            WebviewActivity webviewActivity = WebviewActivity.this;
            mErrorDialog = createDialog(str);
            try {
                mErrorDialog.show();
            } catch (WindowManager.BadTokenException e) {
                e.printStackTrace();
            }
        }

        public void onReceivedSslError(WebView webView, final SslErrorHandler sslErrorHandler, SslError sslError) {
            EPLog.d(TAG, "SSL error: " + sslError);
            if (!isFinishing()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this);
                builder.setIcon(R.drawable.ic_action_warning);
                builder.setTitle("SSL error");
                builder.setMessage(trasrateSslError(sslError.getPrimaryError())).setCancelable(false).setPositiveButton(R.string.str_continue, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        sslErrorHandler.proceed();
                    }
                }).setNegativeButton(getResources().getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        sslErrorHandler.cancel();
                        if (checkSharepage) {
                            boolean unused = checkSharepage = false;
                            setResult(0);
                            finish();
                        }
                    }
                }).show();
            }
        }

        private String trasrateSslError(int i) {
            StringBuffer stringBuffer = new StringBuffer("primaryError = ");
            switch (i) {
                case 0:
                    stringBuffer.append("SSL_NOTYETVALID");
                    break;
                case 1:
                    stringBuffer.append("SSL_EXPIRED");
                    break;
                case 2:
                    stringBuffer.append("SSL_IDMISMATCH");
                    break;
                case 3:
                    stringBuffer.append("SSL_UNTRUSTED");
                    break;
                case 4:
                    stringBuffer.append("SSL_DATE_INVALID ");
                    break;
                case 5:
                    stringBuffer.append("SSL_INVALID");
                    break;
                default:
                    stringBuffer.append(i);
                    break;
            }
            return stringBuffer.toString();
        }

        public void onScaleChanged(WebView webView, float f, float f2) {
            super.onScaleChanged(webView, f, f2);
            float unused = onScaleChangedCurrent = f2;
        }
    };
    private WebChromeClient mWebCromClient = new WebChromeClient() {
        public void onProgressChanged(WebView webView, int i) {
            if (i == 100) {
                mLoadWebLayout.setVisibility(View.GONE);
            }
        }

        public void onReceivedTitle(WebView webView, String str) {
            super.onReceivedTitle(webView, str);
            if (!isBuy && !isFaq && !isInfo) {
                setTitle(str);
            }
        }
    };
    private WebView mWebview;
    Handler myHandler = new Handler() {
        public void handleMessage(Message message) {
            switch (message.what) {
                case 1:
                    Toast.makeText(getBaseContext(), getString(R.string.str_err_msg_out_of_memory_title), 1).show();
                    return;
                case 2:
                    try {
                        Utils.makeMessageBox(this, getString(R.string.str_err_msg_out_of_memory_title), getString(R.string.str_ok)).show();
                        return;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                case 3:
                    if (!mPreviewWebInterrupted) {
                        float access$2000 = getScaleValue();
                        if (mWebview.getProgress() < 100) {
                            myHandler.sendEmptyMessageDelayed(3, 2000);
                            return;
                        } else if (mLastHeight == 0 || mLastHeight < ((((float) mWebview.getContentHeight()) * access$2000))) {
                            WebviewActivity webviewActivity = WebviewActivity.this;
                            int unused = mLastHeight = (((float) mWebview.getContentHeight()) * access$2000);
                            myHandler.sendEmptyMessageDelayed(3, 5000);
                            EPLog.d(TAG, "Waiting not change mLastHeight = " + mLastHeight);
                            return;
                        } else {
                            startPreviewWebThread();
                            return;
                        }
                    } else {
                        return;
                    }
                default:
                    return;
            }
        }
    };
    private float onScaleChangedCurrent = 0.0f;
    private AsyncTask<Void, Void, Void> previewImageTask;
    private SharedPreferences.Editor stateEditor;
    private SharedPreferences statePre;
    private String strUrlIn;
    private EditText teInurl;

    interface InteruptChecker {
        boolean check();
    }

    static /* synthetic */ int access$1308(WebviewActivity webviewActivity) {
        int i = countUrl;
        countUrl = i + 1;
        return i;
    }

    @SuppressLint({"NewApi", "SetJavaScriptEnabled"})
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        NewLoggerController.stopLoggerIfNotAgreed(this);
        if (Build.VERSION.SDK_INT >= 21) {
            WebView.enableSlowWholeDocumentDraw();
        }
        setContentView(R.layout.main_webview);
        setActionBar(R.string.web_btn_label, true);
        mAddImageView.clear();
        ExternalFileUtils.getInstance(this).initTempViewDir();
        ExternalFileUtils.getInstance(this).initPrintDir();
        mWebview = (WebView) findViewById(R.id.web_engine);
        mLoadWebLayout = (LinearLayout) findViewById(R.id.layout_loading);
        teInurl = (EditText) findViewById(R.id.te_url);
        teInurl.setOnKeyListener(this);
        teInurl.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View view, MotionEvent motionEvent) {
                setClearButtonAppearance(0);
                boolean unused = mCanRefresh = false;
                boolean unused2 = mCanClear = true;
                return false;
            }
        });
        mImageArray[0] = Integer.valueOf(R.drawable.clear_text);
        mImageArray[1] = Integer.valueOf(R.drawable.reload);
        btnClearUrl = (ImageButton) findViewById(R.id.btn_clear_url);
        setClearButtonAppearance(0);
        btnClearUrl.setOnClickListener(this);
        WebSettings settings = mWebview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setBuiltInZoomControls(true);
        settings.setUseWideViewPort(true);
        settings.setSupportZoom(true);
        settings.setLoadWithOverviewMode(true);
        settings.setBlockNetworkLoads(false);
        settings.setBlockNetworkImage(false);
        try {
            Method method = mWebview.getClass().getMethod("setIsCacheDrawBitmap", new Class[]{Boolean.TYPE});
            if (method != null) {
                method.invoke(mWebview, new Object[]{false});
                mWebview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
            }
        } catch (NoSuchMethodException unused) {
        } catch (IllegalAccessException unused2) {
        } catch (InvocationTargetException unused3) {
        }
        mWebview.requestFocus(130);
        mWebview.setWebViewClient(mWebClient);
        mWebview.setWebChromeClient(mWebCromClient);
        mWebview.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View view, MotionEvent motionEvent) {
                teInurl.clearFocus();
                mWebview.requestFocus();
                return false;
            }
        });
        mErrorDialog = new AlertDialog.Builder(this).create();
        if (bundle == null) {
            startLicenseCheckActivity();
        } else if (!IprintLicenseInfo.isAgreedCurrentVersion(getApplicationContext())) {
            finish();
        }
    }

    private void startLicenseCheckActivity() {
        IprintLicenseInfo.beforeLicenseCheck(getApplicationContext());
        startActivityForResult(LicenseTopActivity.getStartIntent(getApplicationContext(), new IprintLicenseInfo(), new IprintUserSurveyInfo()), 3);
    }

    private void onInit() {
        configureFromIntent(getIntent());
    }

    /* access modifiers changed from: package-private */
    @VisibleForTesting
    public void configureFromIntent(Intent intent) {
        String action = intent.getAction();
        boolean equals = "android.intent.action.SEND".equals(action);
        boolean equals2 = EpsoniPrintSharedActivity.ACTION_WEB_PRINT.equals(action);
        if (equals || equals2) {
            setPrintLogForExternalApp(intent);
            isCustomAction = equals2;
            inURL = intent.getStringExtra("android.intent.extra.TEXT");
            if (Utils.checkMimeType(this.inURL, "image/jpeg")) {
                checkImage = true;
                previewImage();
            } else {
                loadUrl(this.inURL);
                checkSharepage = !equals;
            }
            String str = inURL;
            if (str != null) {
                strUrlIn = str;
            } else {
                strUrlIn = "";
            }
        } else {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                inURL = intent.getStringExtra("android.intent.extra.TEXT");
                setTitle("Text");
            }
            String str2 = inURL;
            if (str2 == null) {
                mStrictMode.permitAll();
                statePre = getSharedPreferences(CommonDefine.SAVE_URL, 0);
                strUrlIn = statePre.getString(CommonDefine.SAVE_URL, "");
                mStrictMode.restoreStatus();
                if (this.strUrlIn.equals("")) {
                    mIsFistLoad = true;
                    setTextOnUrlEditText(CommonDefine.HTTP_PREFIX);
                    setClearButtonAppearance(1);
                }
                if (extras != null) {
                    inURL = (String) extras.get(CommonDefine.EXTRA_URL);
                    isFaq = extras.getBoolean("is_faq");
                    isBuy = extras.getBoolean("is_buy");
                    isInfo = extras.getBoolean("is_info");
                }
            } else {
                checkSharepage = true;
                strUrlIn = str2;
            }
            String str3 = inURL;
            if (str3 != null) {
                loadUrl(str3);
            } else {
                loadUrl(this.strUrlIn);
            }
            registerForContextMenu(mWebview);
        }
    }

    /* access modifiers changed from: package-private */
    @VisibleForTesting
    public void loadUrl(String str) {
        WiFiDirectManager.setPriorityToSimpleAP(this, false);
        mWebview.loadUrl(str);
    }

    /* access modifiers changed from: package-private */
    @VisibleForTesting
    public void setClearButtonAppearance(int i) {
        btnClearUrl.setBackgroundResource(mImageArray[i].intValue());
    }

    /* access modifiers changed from: package-private */
    @VisibleForTesting
    public void setTextOnUrlEditText(String str) {
        teInurl.setText(str);
    }

    /* access modifiers changed from: package-private */
    @VisibleForTesting
    public void setPrintLogForExternalApp(@Nullable Intent intent) {
        if (intent != null) {
            try {
                mPrintLog = (PrintLog) intent.getSerializableExtra("print_log");
            } catch (ClassCastException unused) {
            }
        }
        if (mPrintLog == null) {
            mPrintLog = new PrintLog();
        }
        if (mPrintLog.uiRoute <= 0) {
            mPrintLog.uiRoute = PrintLog.PRINT_SOURCE_EXTERNAL_APP_WEB;
        }
        if (mPrintLog.callerPackage == null) {
            mPrintLog.callerPackage = getCallingPackage();
        }
    }

    private void loadInputUrl() {
        hideSoftKeyboard();
        String str = strUrlIn;
        if (str != null && str.compareTo("") != 0) {
            if (this.strUrlIn.equals(mWebview.getUrl())) {
                strUrlIn = fixUrl(this.strUrlIn);
                setTextOnUrlEditText(this.strUrlIn);
                mWebview.reload();
                return;
            }
            strUrlIn = fixUrl(this.strUrlIn);
            setTextOnUrlEditText(this.strUrlIn);
            loadUrl(this.strUrlIn);
        }
    }

    private void hideSoftKeyboard() {
        ((InputMethodManager) getSystemService("input_method")).hideSoftInputFromWindow(this.teInurl.getWindowToken(), 0);
    }

    public void onClick(View view) {
        EPLog.i(TAG, "onCLick()");
        if (view.getId() == R.id.btn_clear_url) {
            if (mCanRefresh) {
                mWebview.reload();
            } else if (mCanStop) {
                mWebview.stopLoading();
                mLoadWebLayout.setVisibility(View.GONE);
            } else if (mCanClear) {
                setTextOnUrlEditText("");
            }
        }
    }

    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == 0 && i == 66) {
            mIsFinish = false;
            setClearButtonAppearance(0);
            strUrlIn = teInurl.getText().toString();
            loadInputUrl();
            return true;
        } else if (keyEvent.getAction() != 0 || i != 4 || !this.checkSharepage) {
            return false;
        } else {
            finish();
            return true;
        }
    }

    protected void onPause() {
        super.onPause();
        NfcTagUtils.disableForegroundDispatch(this);
    }

    protected void onResume() {
        super.onResume();
        NfcTagUtils.enableForegroundDispatch(this, (IntentFilter[]) null, (String[][]) null);
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        CommonMessage.showInvalidPrintMessageIfEpsonNfcPrinter(this, intent);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.print_option_menu, menu);
        return true;
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.go_back).setEnabled(canGoBack() && mIsFinish);
        menu.findItem(R.id.go_next).setEnabled(canGoForward() && mIsFinish);
        menu.findItem(R.id.print_option).setEnabled(mIsFinish && !mIsLoadError);
        if (this.checkSharepage) {
            menu.setGroupVisible(0, false);
        }
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem menuItem) {
        int itemId = menuItem.getItemId();
        if (itemId != R.id.print_option) {
            switch (itemId) {
                case R.id.go_back /*2131231074*/:
                    String linkOfIndex = getLinkOfIndex(getIndexOfLink(this.strUrlIn) - 1);
                    EPLog.i("Comeback to : ", linkOfIndex);
                    mWebview.loadUrl(linkOfIndex);
                    break;
                case R.id.go_next /*2131231075*/:
                    String linkOfIndex2 = getLinkOfIndex(getIndexOfLink(this.strUrlIn) + 1);
                    EPLog.i("Forward to : ", linkOfIndex2);
                    mWebview.loadUrl(linkOfIndex2);
                    break;
            }
        } else {
            previewWeb();
        }
        return super.onOptionsItemSelected(menuItem);
    }

    /* access modifiers changed from: private */
    /* JADX WARNING: Removed duplicated region for block: B:11:0x0017  */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public static void saveJPG(Bitmap r2, String r3) throws IOException {
        /*
            r0 = 0
            java.io.FileOutputStream r1 = new java.io.FileOutputStream     // Catch:{ all -> 0x0014 }
            r1.<init>(r3)     // Catch:{ all -> 0x0014 }
            android.graphics.Bitmap$CompressFormat r3 = android.graphics.Bitmap.CompressFormat.JPEG     // Catch:{ all -> 0x0011 }
            r0 = 100
            r2.compress(r3, r0, r1)     // Catch:{ all -> 0x0011 }
            r1.close()
            return
        L_0x0011:
            r2 = move-exception
            r0 = r1
            goto L_0x0015
        L_0x0014:
            r2 = move-exception
        L_0x0015:
            if (r0 == 0) goto L_0x001a
            r0.close()
        L_0x001a:
            throw r2
        */
        throw new UnsupportedOperationException("Method not decompiled: epson.print.saveJPG(android.graphics.Bitmap, java.lang.String):void");
    }

    public void showLoadingDialog() {
        if (mCustomPro == null) {
            mCustomPro = new CustomProDialog(this, R.style.AppTheme_Translucent, R.layout.preview_open_dialog);
            mCustomPro.setCancelable(false);
            mCustomPro.setCanceledOnTouchOutside(false);
        }
        try {
            mCustomPro.show();
        } catch (WindowManager.BadTokenException e) {
            e.printStackTrace();
        }
    }

    public void cancelShowingDialog() {
        Dialog dialog = mCustomPro;
        if (dialog != null && dialog.isShowing()) {
            mCustomPro.dismiss();
        }
    }

    private class CustomProDialog extends Dialog {
        private int mLayoutId;

        public CustomProDialog(Context context, int i, int i2) {
            super(context, i);
            mLayoutId = i2;
        }

        protected void onCreate(Bundle bundle) {
            super.onCreate(bundle);
            requestWindowFeature(1);
            View inflate = getLayoutInflater().inflate(mLayoutId, (ViewGroup) null);
            ((Button) inflate.findViewById(R.id.close_btn)).setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    if (checkSharepage) {
                        mWebview.stopLoading();
                        finish();
                    }
                    stopDoBackGroundThread();
                }
            });
            setContentView(inflate);
        }

        public void onBackPressed() {
            stopDoBackGroundThread();
        }
    }

    protected void stopDoBackGroundThread() {
        cancelPreviewWeb();
        AsyncTask<Void, Void, Void> asyncTask = previewImageTask;
        if (asyncTask != null) {
            asyncTask.cancel(true);
        }
        ImageCreateThread imageCreateThread = mImageCreateThread;
        if (imageCreateThread != null) {
            imageCreateThread.interrupt();
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        stopDoBackGroundThread();
        previewImageTask = null;
        mImageCreateThread = null;
        Dialog dialog = mCustomPro;
        if (dialog != null) {
            dialog.dismiss();
        }
        mCustomPro = null;
        AlertDialog alertDialog = mErrorDialog;
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        mErrorDialog = null;
    }

    private void startPrintActivity() {
        Intent intent = new Intent(this, ActivityPrintWeb.class);
        intent.putStringArrayListExtra("print_web", mAddImageView);
        intent.putExtra("print_url", strUrlIn);
        intent.putExtra("from_customaction", isCustomAction);
        intent.putExtra("print_log", getPrintLog());
        startActivityForResult(intent, 2);
        cancelShowingDialog();
        if (this.checkSharepage && !this.isCustomAction) {
            finish();
        }
    }

    private PrintLog getPrintLog() {
        PrintLog printLog = mPrintLog;
        if (printLog == null) {
            printLog = new PrintLog();
        }
        if (printLog.uiRoute <= 0) {
            printLog.uiRoute = 3;
        }
        if (printLog.originalFileExtension == null) {
            printLog.originalFileExtension = Analytics.EXTENSION_STRING_WEB;
        }
        return printLog;
    }

    class ImageFileCreator {
        static final int A4_360DPI_HEIGHT = 4209;
        static final int A4_360DPI_WIDTH = 2976;
        static final double A4_ASPECT_RATIO = 1.4143145161290323d;
        final int[] RATE_FROME_360DPI = {2, 3, 4};
        Bitmap mBitmap;
        double mExRate;
        Rect mPictureSize;

        ImageFileCreator() {
        }

        public void setPicture(Rect rect) {
            mPictureSize = rect;
        }

        private double[] getExRateCand(int i) {
            double[] dArr = new double[this.RATE_FROME_360DPI.length];
            int i2 = 0;
            while (true) {
                int[] iArr = RATE_FROME_360DPI;
                if (i2 >= iArr.length) {
                    return dArr;
                }
                dArr[i2] = 2976.0d / ((i) * (iArr[i2]));
                i2++;
            }
        }

        public boolean prepareBitmap() {
            int width = mPictureSize.width();
            double[] exRateCand = getExRateCand(width);
            int i = 90;
            double d = 1.0d;
            Bitmap bitmap = null;
            for (int i2 = 0; i2 < exRateCand.length && bitmap == null; i2++) {
                d = exRateCand[i2];
                int i3 = ((width) * d);
                int i4 = ((i3) * A4_ASPECT_RATIO);
                try {
                    System.gc();
                    bitmap = Bitmap.createBitmap(i3, i4, Bitmap.Config.ARGB_8888);
                    i = 360 / RATE_FROME_360DPI[i2];
                } catch (OutOfMemoryError unused) {
                }
            }
            if (bitmap == null) {
                return false;
            }
            bitmap.setDensity(i);
            mBitmap = bitmap;
            mExRate = d;
            EPLog.i(TAG, "expand => " + d);
            return true;
        }

        public boolean createImageFile(final WebView webView, ArrayList<String> arrayList, InteruptChecker interuptChecker) throws IOException {
            double d = mExRate;
            final Object obj = new Object();
            final Canvas canvas = new Canvas(mBitmap);
            float f = (float) d;
            canvas.scale(f, f);
            int width = ((mPictureSize.width()) * A4_ASPECT_RATIO);
            int height = mPictureSize.height();
            int i = 1;
            while (height > 0) {
                if (interuptChecker.check()) {
                    return false;
                }
                String tempViewDir = ExternalFileUtils.getInstance(this).getTempViewDir();
                String path = new File(tempViewDir, "multi_cut_" + i + ".jpg").getPath();
                canvas.drawRGB(255, 255, 255);
                synchronized (obj) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            synchronized (obj) {
                                webView.draw(canvas);
                                obj.notifyAll();
                                EPLog.v(TAG, "webView.draw() finish");
                            }
                        }
                    });
                    try {
                        EPLog.v(TAG, "webView.draw() wait page = " + i);
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                saveJPG(mBitmap, path);
                arrayList.add(path);
                height -= width;
                canvas.translate(0.0f, -((float) width));
                i++;
            }
            return true;
        }

        public void freeMemory() {
            Bitmap bitmap = mBitmap;
            if (bitmap != null) {
                bitmap.recycle();
                mBitmap = null;
            }
        }
    }

    private void previewWeb() {
        mPreviewWebInterrupted = false;
        captureStart = true;
        showLoadingDialog();
        if (this.checkSharepage) {
            myHandler.sendEmptyMessage(3);
        } else {
            startPreviewWebThread();
        }
    }

    private void cancelPreviewWeb() {
        mPreviewWebInterrupted = true;
        myHandler.removeMessages(3);
        ImageCreateThread imageCreateThread = mImageCreateThread;
        if (imageCreateThread != null) {
            imageCreateThread.interrupt();
        }
        cancelShowingDialog();
    }

    private void startPreviewWebThread() {
        mAddImageView.clear();
        float scaleValue = getScaleValue();
        Rect rect = new Rect(0, 0, mWebview.getWidth(), (((float) mWebview.getContentHeight()) * scaleValue));
        EPLog.i(TAG, "picture Rect = " + rect.toString() + " currentScale = " + scaleValue);
        if (rect.width() > 0 && rect.height() > 0) {
            mImageCreateThread = new ImageCreateThread();
            mImageCreateThread.setPicture(rect);
            mImageCreateThread.start();
        } else if (!isFinishing()) {
            cancelShowingDialog();
            mErrorDialog = createDialog(getString(R.string.not_support_format));
            try {
                mErrorDialog.show();
            } catch (WindowManager.BadTokenException unused) {
            }
        }
    }

    private float getScaleValue() {
        float f = onScaleChangedCurrent;
        return f == 0.0f ? getResources().getDisplayMetrics().density : f;
    }

    class ImageCreateThread extends Thread implements InteruptChecker {
        private ImageFileCreator mImageFileCreator;
        private Rect mPicture;

        ImageCreateThread() {
        }

        public ImageCreateThread setPicture(Rect rect) {
            mPicture = rect;
            return this;
        }

        public void run() {
            if (!mPreviewWebInterrupted) {
                ExternalFileUtils.getInstance(this).initTempViewDir();
                mImageFileCreator = new ImageFileCreator();
                mImageFileCreator.setPicture(mPicture);
                if (!mImageFileCreator.prepareBitmap()) {
                    ExternalFileUtils.getInstance(this).initTempViewDir();
                    cancelShowingDialog();
                    myHandler.sendEmptyMessage(1);
                    finish();
                } else if (isInterrupted()) {
                    freeLargeMem();
                    ExternalFileUtils.getInstance(this).initTempViewDir();
                    cancelShowingDialog();
                } else {
                    try {
                        if (!mImageFileCreator.createImageFile(mWebview, mAddImageView, this) || isInterrupted()) {
                            ExternalFileUtils.getInstance(this).initTempViewDir();
                            cancelShowingDialog();
                            return;
                        }
                        startPrintActivity();
                    } catch (IOException e) {
                        e.printStackTrace();
                        ExternalFileUtils.getInstance(this).initTempViewDir();
                        cancelShowingDialog();
                        myHandler.sendEmptyMessage(2);
                    } finally {
                        freeLargeMem();
                    }
                }
            }
        }

        private void freeLargeMem() {
            ImageFileCreator imageFileCreator = mImageFileCreator;
            if (imageFileCreator != null) {
                imageFileCreator.freeMemory();
                mImageFileCreator = null;
            }
            mPicture = null;
        }

        public boolean check() {
            return isInterrupted();
        }
    }

    private AlertDialog createDialog(final String str) {
        AlertDialog create = new AlertDialog.Builder(this).create();
        create.setCancelable(false);
        create.setIcon(R.drawable.ic_action_warning);
        create.setTitle(R.string.unknow_error_title);
        create.setMessage(str);
        create.setButton(-1, getString(R.string.str_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                if (str.equals(getString(R.string.str_no_sdcard))) {
                    cancelShowingDialog();
                    if (checkImage || checkSharepage) {
                        finish();
                    }
                }
            }
        });
        create.setOnKeyListener(new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                return keyEvent.getKeyCode() == 84;
            }
        });
        return create;
    }

    /* access modifiers changed from: package-private */
    @VisibleForTesting
    public void previewImage() {
        if (isMediaMounted()) {
            previewImageTask = new AsyncTask<Void, Void, Void>() {
                ArrayList<String> imagePath = new ArrayList<>();

                protected void onPreExecute() {
                    super.onPreExecute();
                    showLoadingDialog();
                }

                protected Void doInBackground(Void... voidArr) {
                    Uri parse = Uri.parse(inURL);
                    if (String.valueOf(BoxFile.TYPE).equals(parse.getScheme())) {
                        imagePath.add(parse.getPath());
                    } else {
                        String lastPathSegment = parse.getLastPathSegment();
                        String downloadDir = ExternalFileUtils.getInstance(this).getDownloadDir();
                        ExternalFileUtils.getInstance(this).initDownloadDir();
                        if (isCancelled()) {
                            return null;
                        }
                        epson.print.Util.Utils.getInstance();
                        epson.print.Util.Utils.mUtils.downloadFile(inURL, downloadDir, lastPathSegment, this);
                        imagePath.add(new File(downloadDir, lastPathSegment).getPath());
                    }
                    return null;
                }

                protected void onPostExecute(Void voidR) {
                    EPLog.i(TAG, "previewImage::onPostExecute() Share image: " + imagePath.toString());
                    WebviewActivity webviewActivity = this;
                    Intent unused = mIntent = new Intent(webviewActivity, ActivityViewImageSelect.class);
                    mIntent.putExtra(ActivityViewImageSelect.LIST_ALBUM, imagePath);
                    mIntent.putExtra(CommonDefine.STYPE, true);
                    mIntent.putExtra("print_log", getPrintLog());
                    WebviewActivity webviewActivity2 = this;
                    webviewActivity2.startActivity(webviewActivity2.mIntent);
                    finish();
                }

                protected void onCancelled() {
                    EPLog.i(TAG, "Cancel: OK");
                    if (checkImage) {
                        finish();
                    }
                }
            };
            previewImageTask.execute(new Void[0]);
            return;
        }
        mErrorDialog = createDialog(getString(R.string.str_no_sdcard));
        try {
            findViewById(R.id.webview).setVisibility(4);
            mErrorDialog.show();
        } catch (WindowManager.BadTokenException e) {
            e.printStackTrace();
        }
    }

    /* access modifiers changed from: package-private */
    @VisibleForTesting
    public boolean isMediaMounted() {
        return Utils.isMediaMounted();
    }

    private String fixUrl(String str) {
        int indexOf = str.indexOf(58);
        String str2 = str;
        boolean z = true;
        for (int i = 0; i < indexOf; i++) {
            char charAt = str2.charAt(i);
            if (!Character.isLetter(charAt)) {
                break;
            }
            z &= Character.isLowerCase(charAt);
            if (i == indexOf - 1 && !z) {
                str2 = str2.substring(0, indexOf).toLowerCase() + str2.substring(indexOf);
            }
        }
        if (str2.startsWith(CommonDefine.HTTP_PREFIX) || str2.startsWith("https://")) {
            return str2;
        }
        if (str2.startsWith("http:") || str2.startsWith("https:")) {
            if (str2.startsWith("http:/") || str2.startsWith("https:/")) {
                str2 = str2.replaceFirst(CommonDefine.SLASH, "//");
            } else {
                str2 = str2.replaceFirst(":", "://");
            }
        }
        if (!str2.startsWith(CommonDefine.HTTP_PREFIX) && !str2.startsWith("file://")) {
            str2 = CommonDefine.HTTP_PREFIX + str2;
        }
        return str2.toLowerCase();
    }

    public void onBackPressed() {
        AlertDialog alertDialog = mErrorDialog;
        if (alertDialog != null && alertDialog.isShowing()) {
            try {
                mErrorDialog.dismiss();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        ImageCreateThread imageCreateThread = mImageCreateThread;
        if (imageCreateThread != null) {
            imageCreateThread.interrupt();
        }
        if (this.isBuy || isFaq || isInfo) {
            finish();
        } else if (this.isCustomAction) {
            setResult(0);
            finish();
        } else {
            setResult(-1, getIntent());
            finish();
        }
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        EPLog.d("onActivityResult : requestCode = ", String.valueOf(i));
        super.onActivityResult(i, i2, intent);
        switch (i) {
            case 2:
                EPLog.d("onActivityResult : ACTION_PRINT_WEB = ", String.valueOf(this.isCustomAction));
                mAddImageView.clear();
                ExternalFileUtils.getInstance(this).initTempViewDir();
                if (this.isCustomAction) {
                    EPLog.d("onActivityResult : resultCode = ", String.valueOf(i2));
                    setResult(i2);
                    finish();
                    return;
                }
                return;
            case 3:
                if (i2 != -1) {
                    finish();
                    return;
                } else {
                    onInit();
                    return;
                }
            default:
                return;
        }
    }

    private int getIndexOfLink(String str) {
        int i = 0;
        for (int i2 = 0; i2 < mListUrl.size(); i2++) {
            if (str.equalsIgnoreCase((String) mListUrl.get(i2).get(BoxRequestsMetadata.UpdateItemMetadata.BoxMetadataUpdateTask.VALUE))) {
                i = Integer.parseInt((String) mListUrl.get(i2).get("key"));
            }
        }
        return i;
    }

    private String getLinkOfIndex(int i) {
        String str = "";
        for (int i2 = 0; i2 < mListUrl.size(); i2++) {
            if (Integer.parseInt((String) mListUrl.get(i2).get("key")) == i) {
                str = (String) mListUrl.get(i2).get(BoxRequestsMetadata.UpdateItemMetadata.BoxMetadataUpdateTask.VALUE);
            }
        }
        return str;
    }

    private boolean canGoBack() {
        return getIndexOfLink(this.strUrlIn) > 1;
    }

    private boolean canGoForward() {
        return getIndexOfLink(this.strUrlIn) < mListUrl.size();
    }
}
