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.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
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 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;
    /* access modifiers changed from: private */
    public boolean captureStart = false;
    /* access modifiers changed from: private */
    public boolean checkImage = false;
    /* access modifiers changed from: private */
    public boolean checkSharepage = false;
    /* access modifiers changed from: private */
    public int countUrl;
    /* access modifiers changed from: private */
    public String inURL = null;
    boolean isBuy = false;
    private boolean isCustomAction = false;
    boolean isFaq = false;
    boolean isInfo = false;
    /* access modifiers changed from: private */
    public ArrayList<String> mAddImageView = new ArrayList<>();
    /* access modifiers changed from: private */
    public boolean mCanClear;
    /* access modifiers changed from: private */
    public boolean mCanRefresh;
    /* access modifiers changed from: private */
    public boolean mCanStop;
    private Dialog mCustomPro;
    public AlertDialog mErrorDialog;
    private Integer[] mImageArray = new Integer[2];
    private ImageCreateThread mImageCreateThread;
    /* access modifiers changed from: private */
    public Intent mIntent;
    boolean mIsBookmark;
    boolean mIsBookmarkEmpty;
    /* access modifiers changed from: private */
    public boolean mIsFinish;
    boolean mIsFistLoad;
    boolean mIsLoadError = false;
    private MenuItem[] mItem = new MenuItem[6];
    /* access modifiers changed from: private */
    public int mLastHeight = 0;
    /* access modifiers changed from: private */
    public ArrayList<HashMap<String, String>> mListUrl = new ArrayList<>();
    /* access modifiers changed from: private */
    public LinearLayout mLoadWebLayout;
    /* access modifiers changed from: private */
    public 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 (!WebviewActivity.this.checkSharepage) {
                WebviewActivity.this.mLoadWebLayout.setVisibility(0);
            } else {
                WebviewActivity.this.showLoadingDialog();
            }
            WebviewActivity webviewActivity = WebviewActivity.this;
            webviewActivity.setTextOnUrlEditText(webviewActivity.fixUrl(str));
            boolean unused = WebviewActivity.this.mIsFinish = false;
            boolean unused2 = WebviewActivity.this.mCanStop = true;
            WebviewActivity.this.setClearButtonAppearance(0);
            boolean unused3 = WebviewActivity.this.mCanRefresh = false;
            WebviewActivity.this.invalidateOptionsMenu();
        }

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

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

        public void onReceivedSslError(WebView webView, final SslErrorHandler sslErrorHandler, SslError sslError) {
            EPLog.m305d(WebviewActivity.TAG, "SSL error: " + sslError);
            if (!WebviewActivity.this.isFinishing()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this);
                builder.setIcon(R.C2136drawable.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(WebviewActivity.this.getResources().getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        sslErrorHandler.cancel();
                        if (WebviewActivity.this.checkSharepage) {
                            boolean unused = WebviewActivity.this.checkSharepage = false;
                            WebviewActivity.this.setResult(0);
                            WebviewActivity.this.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 = WebviewActivity.this.onScaleChangedCurrent = f2;
        }
    };
    private WebChromeClient mWebCromClient = new WebChromeClient() {
        public void onProgressChanged(WebView webView, int i) {
            if (i == 100) {
                WebviewActivity.this.mLoadWebLayout.setVisibility(8);
            }
        }

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

    interface InteruptChecker {
        boolean check();
    }

    static /* synthetic */ int access$1308(WebviewActivity webviewActivity) {
        int i = webviewActivity.countUrl;
        webviewActivity.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((int) R.layout.main_webview);
        setActionBar((int) R.string.web_btn_label, true);
        this.mAddImageView.clear();
        ExternalFileUtils.getInstance(this).initTempViewDir();
        ExternalFileUtils.getInstance(this).initPrintDir();
        this.mWebview = (WebView) findViewById(R.id.web_engine);
        this.mLoadWebLayout = (LinearLayout) findViewById(R.id.layout_loading);
        this.teInurl = (EditText) findViewById(R.id.te_url);
        this.teInurl.setOnKeyListener(this);
        this.teInurl.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View view, MotionEvent motionEvent) {
                WebviewActivity.this.setClearButtonAppearance(0);
                boolean unused = WebviewActivity.this.mCanRefresh = false;
                boolean unused2 = WebviewActivity.this.mCanClear = true;
                return false;
            }
        });
        this.mImageArray[0] = Integer.valueOf(R.C2136drawable.clear_text);
        this.mImageArray[1] = Integer.valueOf(R.C2136drawable.reload);
        this.btnClearUrl = (ImageButton) findViewById(R.id.btn_clear_url);
        setClearButtonAppearance(0);
        this.btnClearUrl.setOnClickListener(this);
        WebSettings settings = this.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 = this.mWebview.getClass().getMethod("setIsCacheDrawBitmap", new Class[]{Boolean.TYPE});
            if (method != null) {
                method.invoke(this.mWebview, new Object[]{false});
                this.mWebview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
            }
        } catch (NoSuchMethodException unused) {
        } catch (IllegalAccessException unused2) {
        } catch (InvocationTargetException unused3) {
        }
        this.mWebview.requestFocus(130);
        this.mWebview.setWebViewClient(this.mWebClient);
        this.mWebview.setWebChromeClient(this.mWebCromClient);
        this.mWebview.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View view, MotionEvent motionEvent) {
                WebviewActivity.this.teInurl.clearFocus();
                WebviewActivity.this.mWebview.requestFocus();
                return false;
            }
        });
        this.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);
            this.isCustomAction = equals2;
            this.inURL = intent.getStringExtra("android.intent.extra.TEXT");
            if (Utils.checkMimeType(this.inURL, "image/jpeg")) {
                this.checkImage = true;
                previewImage();
            } else {
                loadUrl(this.inURL);
                this.checkSharepage = !equals;
            }
            String str = this.inURL;
            if (str != null) {
                this.strUrlIn = str;
            } else {
                this.strUrlIn = "";
            }
        } else {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                this.inURL = intent.getStringExtra("android.intent.extra.TEXT");
                setTitle("Text");
            }
            String str2 = this.inURL;
            if (str2 == null) {
                this.mStrictMode.permitAll();
                this.statePre = getSharedPreferences(CommonDefine.SAVE_URL, 0);
                this.strUrlIn = this.statePre.getString(CommonDefine.SAVE_URL, "");
                this.mStrictMode.restoreStatus();
                if (this.strUrlIn.equals("")) {
                    this.mIsFistLoad = true;
                    setTextOnUrlEditText(CommonDefine.HTTP_PREFIX);
                    setClearButtonAppearance(1);
                }
                if (extras != null) {
                    this.inURL = (String) extras.get(CommonDefine.EXTRA_URL);
                    this.isFaq = extras.getBoolean("is_faq");
                    this.isBuy = extras.getBoolean("is_buy");
                    this.isInfo = extras.getBoolean("is_info");
                }
            } else {
                this.checkSharepage = true;
                this.strUrlIn = str2;
            }
            String str3 = this.inURL;
            if (str3 != null) {
                loadUrl(str3);
            } else {
                loadUrl(this.strUrlIn);
            }
            registerForContextMenu(this.mWebview);
        }
    }

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

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

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

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

    private void loadInputUrl() {
        hideSoftKeyboard();
        String str = this.strUrlIn;
        if (str != null && str.compareTo("") != 0) {
            if (this.strUrlIn.equals(this.mWebview.getUrl())) {
                this.strUrlIn = fixUrl(this.strUrlIn);
                setTextOnUrlEditText(this.strUrlIn);
                this.mWebview.reload();
                return;
            }
            this.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.m313i(TAG, "onCLick()");
        if (view.getId() == R.id.btn_clear_url) {
            if (this.mCanRefresh) {
                this.mWebview.reload();
            } else if (this.mCanStop) {
                this.mWebview.stopLoading();
                this.mLoadWebLayout.setVisibility(8);
            } else if (this.mCanClear) {
                setTextOnUrlEditText("");
            }
        }
    }

    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == 0 && i == 66) {
            this.mIsFinish = false;
            setClearButtonAppearance(0);
            this.strUrlIn = this.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.C2138menu.print_option_menu, menu);
        return true;
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.go_back).setEnabled(canGoBack() && this.mIsFinish);
        menu.findItem(R.id.go_next).setEnabled(canGoForward() && this.mIsFinish);
        menu.findItem(R.id.print_option).setEnabled(this.mIsFinish && !this.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.m313i("Comeback to : ", linkOfIndex);
                    this.mWebview.loadUrl(linkOfIndex);
                    break;
                case R.id.go_next /*2131231075*/:
                    String linkOfIndex2 = getLinkOfIndex(getIndexOfLink(this.strUrlIn) + 1);
                    EPLog.m313i("Forward to : ", linkOfIndex2);
                    this.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.WebviewActivity.saveJPG(android.graphics.Bitmap, java.lang.String):void");
    }

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

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

    private class CustomProDialog extends Dialog {
        private int mLayoutId;

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

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

        public void onBackPressed() {
            WebviewActivity.this.stopDoBackGroundThread();
        }
    }

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

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

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

    /* access modifiers changed from: private */
    public PrintLog getPrintLog() {
        PrintLog printLog = this.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) {
            this.mPictureSize = rect;
        }

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

        public boolean prepareBitmap() {
            int width = this.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 = (int) (((double) width) * d);
                int i4 = (int) (((double) i3) * A4_ASPECT_RATIO);
                try {
                    System.gc();
                    bitmap = Bitmap.createBitmap(i3, i4, Bitmap.Config.ARGB_8888);
                    i = 360 / this.RATE_FROME_360DPI[i2];
                } catch (OutOfMemoryError unused) {
                }
            }
            if (bitmap == null) {
                return false;
            }
            bitmap.setDensity(i);
            this.mBitmap = bitmap;
            this.mExRate = d;
            EPLog.m313i(WebviewActivity.TAG, "expand => " + d);
            return true;
        }

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

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

    /* access modifiers changed from: private */
    public void previewWeb() {
        this.mPreviewWebInterrupted = false;
        this.captureStart = true;
        showLoadingDialog();
        if (this.checkSharepage) {
            this.myHandler.sendEmptyMessage(3);
        } else {
            startPreviewWebThread();
        }
    }

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

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

    /* access modifiers changed from: private */
    public float getScaleValue() {
        float f = this.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) {
            this.mPicture = rect;
            return this;
        }

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

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

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

    /* access modifiers changed from: private */
    public AlertDialog createDialog(final String str) {
        AlertDialog create = new AlertDialog.Builder(this).create();
        create.setCancelable(false);
        create.setIcon(R.C2136drawable.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(WebviewActivity.this.getString(R.string.str_no_sdcard))) {
                    WebviewActivity.this.cancelShowingDialog();
                    if (WebviewActivity.this.checkImage || WebviewActivity.this.checkSharepage) {
                        WebviewActivity.this.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()) {
            this.previewImageTask = new AsyncTask<Void, Void, Void>() {
                ArrayList<String> imagePath = new ArrayList<>();

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

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

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

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

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

    /* access modifiers changed from: private */
    public 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 = this.mErrorDialog;
        if (alertDialog != null && alertDialog.isShowing()) {
            try {
                this.mErrorDialog.dismiss();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        ImageCreateThread imageCreateThread = this.mImageCreateThread;
        if (imageCreateThread != null) {
            imageCreateThread.interrupt();
        }
        if (this.isBuy || this.isFaq || this.isInfo) {
            finish();
        } else if (this.isCustomAction) {
            setResult(0);
            finish();
        } else {
            setResult(-1, getIntent());
            finish();
        }
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        EPLog.m305d("onActivityResult : requestCode = ", String.valueOf(i));
        super.onActivityResult(i, i2, intent);
        switch (i) {
            case 2:
                EPLog.m305d("onActivityResult : ACTION_PRINT_WEB = ", String.valueOf(this.isCustomAction));
                this.mAddImageView.clear();
                ExternalFileUtils.getInstance(this).initTempViewDir();
                if (this.isCustomAction) {
                    EPLog.m305d("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 < this.mListUrl.size(); i2++) {
            if (str.equalsIgnoreCase((String) this.mListUrl.get(i2).get(BoxRequestsMetadata.UpdateItemMetadata.BoxMetadataUpdateTask.VALUE))) {
                i = Integer.parseInt((String) this.mListUrl.get(i2).get("key"));
            }
        }
        return i;
    }

    private String getLinkOfIndex(int i) {
        String str = "";
        for (int i2 = 0; i2 < this.mListUrl.size(); i2++) {
            if (Integer.parseInt((String) this.mListUrl.get(i2).get("key")) == i) {
                str = (String) this.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) < this.mListUrl.size();
    }
}
