package com.epson.mobilephone.common.wifidirect;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Observer;

import java.util.Deque;

public class ActivityConnectP2P extends ActivityConnectBase implements DialogProgressWiFiDirect.DialogButtonClick {
    private static final int DELAY_P2P_CONNECT = 1000;
    private static final String IDD_WIFI_ERROR = "idd_wifi_error";
    private static final String IDD_WIFI_WAITING = "idd_wifi_waiting";
    private static final int ID_CHECK_WIIFISTATE = 11;
    private static final int ID_CONNECTED_WIFI = 10;
    private static final int ID_CONNECT_P2P = 12;
    private static final int ID_FOUND = 1;
    private static final int ID_NOT_FOUND = 2;
    private static final int ID_RESULT = 0;
    private static final int MAX_P2P_CONNECT = 5;
    private static final String TAG = "ActivityConnectP2P";
    Handler mHandler = new Handler() {
        public void handleMessage(Message message) {
            super.handleMessage(message);
            switch (C10835.f149x55760faf[status.ordinal()]) {
                case 1:
                    break;
                case 2:
                    switch (message.what) {
                        case 1:
                            Bundle data = message.getData();
                            if (data != null) {
                                String string = data.getString("name");
                                String string2 = data.getString(escprLib.PRINTER_IP);
                                String string3 = data.getString("id");
                                if (string != null && string2 != null && string3 != null) {
                                    EPLog.i(ActivityConnectP2P.TAG, "epsWrapperFindPrinter Success" + string);
                                    if (!expectedPrtMacAddr.equals(MacAddrUtils.getMacAddressFromPrinterId(string3))) {
                                        EPLog.i(ActivityConnectP2P.TAG, "This Printer is not expected " + string);
                                        return;
                                    }
                                    interruptFindingPrinter();
                                    Intent intent = new Intent();
                                    intent.putExtras(data);
                                    onConnectedPrinter(intent);
                                    return;
                                }
                                return;
                            }
                            return;
                        case 2:
                            onError();
                            return;
                        default:
                            return;
                    }
                case 3:
                    if (message.what == 11) {
                        if (!ActivityConnectP2P.mWifiManager.isWifiEnabled()) {
                            startActivityForResult(new Intent(ActivityConnectP2P.this, ActivityControlWiFi.class), 1);
                            return;
                        }
                        onEnabledWifi();
                        return;
                    }
                    return;
                case 4:
                    if (message.what == 0) {
                        Bundle data2 = message.getData();
                        if (data2 != null && !data2.isEmpty()) {
                            if (targetSsid.equals(WiFiControl.removeSSIDPrefix(data2.getString("ssid")))) {
                                WifiP2pConfig unused = p2pConnectConfig = new WifiP2pConfig();
                                p2pConnectConfig.deviceAddress = data2.getString(SearchWiFiDirectPrinterTask.MACADDR_P2P);
                                p2pConnectConfig.groupOwnerIntent = -1;
                                p2pConnectConfig.wps.setup = 0;
                                status = ActivityConnectBase.Status.WIFI_CONNECTING;
                                setupObserver();
                                ActivityConnectP2P.mHandler.sendEmptyMessage(12);
                                break;
                            }
                        } else {
                            EPLog.e(ActivityConnectP2P.TAG, "Not Found Network");
                            status = ActivityConnectBase.Status.IDLE;
                            onError();
                            break;
                        }
                    }
                    break;
                default:
                    return;
            }
            int i = message.what;
            if (i == 10) {
                status = ActivityConnectBase.Status.WIFI_CONNECTED;
                onConnectedWiFi();
            } else if (i == 12) {
                EPLog.d(ActivityConnectP2P.TAG, "connect() " + targetSsid);
                ActivityConnectP2P.mWiFiP2PManager.connect(p2pChannnel, p2pConnectConfig, new WifiP2pManager.ActionListener() {
                    public void onSuccess() {
                        EPLog.d(ActivityConnectP2P.TAG, "P2PConnect_Operation Success");
                    }

                    public void onFailure(int i) {
                        if (i == 0) {
                            EPLog.w(ActivityConnectP2P.TAG, "P2PConnect_Operation Error " + i);
                            if (searchWiFiDirectPrinter == null) {
                                onError();
                            } else if (p2pRetryCount < 5) {
                                searchWiFiDirectPrinter.interrupt();
                                interruptConnecting();
                                onActivityResult(2, -1, (Intent) null);
                                ActivityConnectP2P.access$408(ActivityConnectP2P.this);
                            } else {
                                onError();
                            }
                        } else if (i != 2) {
                            EPLog.w(ActivityConnectP2P.TAG, "P2PConnect_Operation Fail " + i);
                            onError();
                        } else {
                            EPLog.w(ActivityConnectP2P.TAG, "P2PConnect_Operation BUSY");
                            ActivityConnectP2P.mHandler.sendEmptyMessageDelayed(12, 1000);
                        }
                    }
                });
            }
        }
    };
    private DialogProgressWiFiDirectViewModel mModelDialog;
    WifiP2pManager mWiFiP2PManager = null;
    WifiP2pManager.Channel p2pChannnel = null;
    private WifiP2pConfig p2pConnectConfig = null;
    private int p2pRetryCount = 0;
    WiFiDirectBroadcastReceiver p2pStateChangeReciever = null;

    public void onCancelDialog(String str) {
    }

    public void onNegativeClick(String str) {
    }

    public void onNeutralClick(String str) {
    }

    static /* synthetic */ int access$408(ActivityConnectP2P activityConnectP2P) {
        int i = activityConnectP2P.p2pRetryCount;
        activityConnectP2P.p2pRetryCount = i + 1;
        return i;
    }

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        mModelDialog = (DialogProgressWiFiDirectViewModel) ViewModelProviders.m2of((FragmentActivity) this).get(DialogProgressWiFiDirectViewModel.class);
        mModelDialog.getDialogJob().observe(this, new Observer<Deque<String[]>>() {
            public void onChanged(@Nullable Deque<String[]> deque) {
                String[] checkQueue = ActivityConnectP2P.mModelDialog.checkQueue();
                if (checkQueue != null) {
                    String str = checkQueue[0];
                    String str2 = checkQueue[1];
                    if (str2.equals("do_show")) {
                        showDialog(str);
                    }
                    if (str2.equals("do_dismiss")) {
                        dismissDialog(str);
                    }
                }
            }
        });
        mModelDialog.doShow(IDD_WIFI_WAITING);
        mWiFiP2PManager = (WifiP2pManager) getSystemService("wifip2p");
        WifiP2pManager wifiP2pManager = mWiFiP2PManager;
        if (wifiP2pManager != null) {
            p2pChannnel = wifiP2pManager.initialize(this, getMainLooper(), (WifiP2pManager.ChannelListener) null);
        }
        if (mWiFiP2PManager == null || p2pChannnel == null) {
            onError();
            return;
        }
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            targetSsid = extras.getString(ActivityConnectBase.APNAME);
            showErrorDlg = extras.getBoolean(ActivityConnectBase.SHOWERROR, false);
            showConnectedTip = extras.getBoolean(ActivityConnectBase.SHOWTIP, true);
            needInfo = extras.getBoolean(ActivityConnectBase.NEEDINFO, false);
            timeout = extras.getInt(ActivityConnectBase.TIMEOUT, 30);
        }
        EPLog.i(TAG, "Starting connect :" + targetSsid + " timeout = " + timeout);
        if (Build.VERSION.SDK_INT >= 29) {
            ActivityRequestLocationPermission.requestLocationPermissionForce(this, 2);
        } else {
            mHandler.sendEmptyMessage(11);
        }
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i != 2) {
            if (i == 5) {
                onEnabledWifi();
            }
        } else if (i2 != -1) {
            closeWaitingDialog();
            setResult(0);
            setLastDetailResult(1);
            finish();
        } else {
            mHandler.sendEmptyMessage(11);
        }
    }

    protected void onEnabledWifi() {
        WiFiUtils instance = WiFiUtils.getInstance(this);
        String curSSID = instance.getCurSSID();
        if (!WiFiControl.isSimpleAP(curSSID) || instance.invalidateSimpleAP(this, instance.getCurNetworkId())) {
            WifiP2pUtils.ConnectionInfo connectionInfo = WifiP2pUtils.getInstance(this).getConnectionInfo();
            if (connectionInfo != null) {
                if (targetSsid.equals(connectionInfo.printerName)) {
                    EPLog.d(TAG, "Already Connected!!");
                    status = ActivityConnectBase.Status.WIFI_CONNECTING;
                    mHandler.sendEmptyMessage(10);
                    return;
                }
                WifiP2pUtils.getInstance(this).disconnect();
            }
            if (!this.searchWiFiDirectPrinter.start(2, mHandler, 0, timeout)) {
                onError();
            } else {
                status = ActivityConnectBase.Status.WIFI_SCANNING;
            }
        } else {
            AlertDialog.Builder negativeButton = new AlertDialog.Builder(this).setTitle(R.string.str_error_wifi_connecting_failed).setPositiveButton(getString(R.string.str_goto_wifi_setting), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    EPLog.d(ActivityConnectP2P.TAG, "finish():GOTO_WIFI_SETTINGS");
                    WiFiUtils.showOsWifiSettings(ActivityConnectP2P.this, 5);
                }
            }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    EPLog.d(ActivityConnectP2P.TAG, "finish():RESULT_CANCELED");
                    onError();
                    ActivityConnectBase.setLastDetailResult(1);
                }
            });
            negativeButton.setMessage(getString(R.string.str_notice_delete_simpleAP) + "\n\nSSID: " + curSSID).setCancelable(false).show();
        }
    }

    /* access modifiers changed from: private */
    /* JADX WARNING: Removed duplicated region for block: B:12:0x0028  */
    /* JADX WARNING: Removed duplicated region for block: B:13:0x002a  */
    /* JADX WARNING: Removed duplicated region for block: B:14:0x0041  */
    /* JADX WARNING: Removed duplicated region for block: B:16:0x0058  */
    /* JADX WARNING: Removed duplicated region for block: B:18:? A[RETURN, SYNTHETIC] */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public void showDialog(java.lang.String r11) {
        /*
            r10 = this;
            int r0 = r11.hashCode()
            r1 = -174410503(0xfffffffff59ab4f9, float:-3.9222865E32)
            r2 = 0
            if (r0 == r1) goto L_0x001a
            r1 = 765832116(0x2da5abb4, float:1.883458E-11)
            if (r0 == r1) goto L_0x0010
            goto L_0x0024
        L_0x0010:
            java.lang.String r0 = "idd_wifi_error"
            boolean r0 = r11.equals(r0)
            if (r0 == 0) goto L_0x0024
            r0 = 1
            goto L_0x0025
        L_0x001a:
            java.lang.String r0 = "idd_wifi_waiting"
            boolean r0 = r11.equals(r0)
            if (r0 == 0) goto L_0x0024
            r0 = 0
            goto L_0x0025
        L_0x0024:
            r0 = -1
        L_0x0025:
            switch(r0) {
                case 0: goto L_0x0041;
                case 1: goto L_0x002a;
                default: goto L_0x0028;
            }
        L_0x0028:
            r0 = 0
            goto L_0x0056
        L_0x002a:
            r4 = 2
            int r0 = com.epson.mobilephone.common.wifidirect.R.string.str_error_connecting_printer_p2p
            java.lang.String r5 = r10.getString(r0)
            r6 = 0
            r0 = 17039370(0x104000a, float:2.42446E-38)
            java.lang.String r7 = r10.getString(r0)
            r8 = 0
            r9 = 0
            r3 = r11
            com.epson.mobilephone.common.wifidirect.DialogProgressWiFiDirect r0 = com.epson.mobilephone.common.wifidirect.DialogProgressWiFiDirect.newInstance(r3, r4, r5, r6, r7, r8, r9)
            goto L_0x0056
        L_0x0041:
            r4 = 0
            int r0 = com.epson.mobilephone.common.wifidirect.R.string.str_connecting_printer_p2p
            java.lang.String r5 = r10.getString(r0)
            r6 = 0
            int r0 = com.epson.mobilephone.common.wifidirect.R.string.str_cancel
            java.lang.String r7 = r10.getString(r0)
            r8 = 0
            r9 = 0
            r3 = r11
            com.epson.mobilephone.common.wifidirect.DialogProgressWiFiDirect r0 = com.epson.mobilephone.common.wifidirect.DialogProgressWiFiDirect.newInstance(r3, r4, r5, r6, r7, r8, r9)
        L_0x0056:
            if (r0 == 0) goto L_0x0062
            r0.setCancelable(r2)
            android.support.v4.app.FragmentManager r1 = r10.getSupportFragmentManager()
            r0.show(r1, r11)
        L_0x0062:
            return
        */
        throw new UnsupportedOperationException("Method not decompiled: com.epson.mobilephone.common.wifidirect.ActivityConnectP2P.showDialog(java.lang.String):void");
    }

    private void dismissDialog(String str) {
        DialogFragment dialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(str);
        if (dialogFragment != null) {
            dialogFragment.dismiss();
        }
    }

    protected void interruptConnecting() {
        super.interruptConnecting();
        WiFiDirectBroadcastReceiver wiFiDirectBroadcastReceiver = p2pStateChangeReciever;
        if (wiFiDirectBroadcastReceiver != null) {
            try {
                unregisterReceiver(wiFiDirectBroadcastReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            p2pStateChangeReciever = null;
        }
    }

    private void onConnectedWiFi() {
        EPLog.d(TAG, "onConnect()");
        interruptConnecting();
        ManageDefaultNetwork.getInstance(this).resetDefaultNetwork();
        if (showConnectedTip) {
            Toast.makeText(this, getString(R.string.str_notice_wifi_connected), 0).show();
        }
        if (!this.needInfo) {
            closeWaitingDialog();
            status = ActivityConnectBase.Status.IDLE;
            setResult(-1);
            setLastDetailResult(-1);
            finish();
            return;
        }
        if (taskFindPrinter != null) {
            EPLog.w(TAG, "Already called onConnect()");
        }
        WifiP2pUtils.ConnectionInfo connectionInfo = WifiP2pUtils.getInstance(this).getConnectionInfo();
        if (connectionInfo.isGroupOwnerThisDevice) {
            expectedPrtMacAddr = WiFiControl.p2pAddr2PtrAddr(connectionInfo.p2PMacAdder, targetSsid);
        } else {
            expectedPrtMacAddr = WiFiControl.p2pAddr2PtrAddrP2P(connectionInfo.p2PMacAdder, targetSsid);
        }
        status = ActivityConnectBase.Status.PRINTER_FINDING;
        taskFindPrinter = new FindPrinterTask(mHandler, timeout, 1, 2);
        taskFindPrinter.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]);
    }

    private void onError() {
        closeWaitingDialog();
        Toast.makeText(this, getString(R.string.str_error_connecting_printer_short), 1).show();
        if (searchWiFiDirectPrinter != null) {
            searchWiFiDirectPrinter.interrupt();
            searchWiFiDirectPrinter = null;
        }
        switch (status) {
            case WIFI_CONNECTING:
                if (p2pConnectConfig != null) {
                    interruptConnecting();
                    if (mWiFiP2PManager != null) {
                        EPLog.d(TAG, "cancelConnect() " + targetSsid);
                        mWiFiP2PManager.cancelConnect(p2pChannnel, (WifiP2pManager.ActionListener) null);
                        p2pConnectConfig = null;
                        break;
                    }
                }
                break;
            case PRINTER_FINDING:
                if (taskFindPrinter != null) {
                    taskFindPrinter.cancel();
                    taskFindPrinter = null;
                    break;
                }
                break;
        }
        if (showErrorDlg) {
            mModelDialog.doShow(IDD_WIFI_ERROR);
            return;
        }
        EPLog.d(TAG, "finish():RESULT_CANCELED");
        setResult(0);
        setLastDetailResult(2);
        finish();
    }

    private void closeWaitingDialog() {
        EPLog.d(TAG, "Called closeWaitingDialog()");
        try {
            mModelDialog.doDismiss(IDD_WIFI_WAITING);
        } catch (IllegalArgumentException unused) {
            EPLog.d(TAG, "IDD_WIFI_WAITING already closed");
        }
    }

    private void setupObserver() {
        super.setupObserver();
        p2pStateChangeReciever = new WiFiDirectBroadcastReceiver();
        registerReceiver(p2pStateChangeReciever, new IntentFilter("android.net.wifi.p2p.CONNECTION_STATE_CHANGE"));
    }

    /* JADX WARNING: Removed duplicated region for block: B:12:0x0029  */
    /* JADX WARNING: Removed duplicated region for block: B:13:0x003b  */
    /* JADX WARNING: Removed duplicated region for block: B:16:? A[RETURN, SYNTHETIC] */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public void onPositiveClick(java.lang.String r4) {
        /*
            r3 = this;
            int r0 = r4.hashCode()
            r1 = -174410503(0xfffffffff59ab4f9, float:-3.9222865E32)
            r2 = 0
            if (r0 == r1) goto L_0x001a
            r1 = 765832116(0x2da5abb4, float:1.883458E-11)
            if (r0 == r1) goto L_0x0010
            goto L_0x0024
        L_0x0010:
            java.lang.String r0 = "idd_wifi_error"
            boolean r4 = r4.equals(r0)
            if (r4 == 0) goto L_0x0024
            r4 = 1
            goto L_0x0025
        L_0x001a:
            java.lang.String r0 = "idd_wifi_waiting"
            boolean r4 = r4.equals(r0)
            if (r4 == 0) goto L_0x0024
            r4 = 0
            goto L_0x0025
        L_0x0024:
            r4 = -1
        L_0x0025:
            switch(r4) {
                case 0: goto L_0x003b;
                case 1: goto L_0x0029;
                default: goto L_0x0028;
            }
        L_0x0028:
            goto L_0x0040
        L_0x0029:
            java.lang.String r4 = "ActivityConnectP2P"
            java.lang.String r0 = "finish():RESULT_CANCELED"
            com.epson.mobilephone.common.wifidirect.EPLog.m86d(r4, r0)
            r3.setResult(r2)
            r4 = 2
            setLastDetailResult(r4)
            r3.finish()
            goto L_0x0040
        L_0x003b:
            r3.showErrorDlg = r2
            r3.onError()
        L_0x0040:
            return
        */
        throw new UnsupportedOperationException("Method not decompiled: com.epson.mobilephone.common.wifidirect.ActivityConnectP2P.onPositiveClick(java.lang.String):void");
    }

    class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
        WiFiDirectBroadcastReceiver() {
        }

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            EPLog.d(ActivityConnectP2P.TAG, "WiFiDirectBroadcastReceiver:onReceive() action = " + action);
            if (action.equals("android.net.wifi.p2p.CONNECTION_STATE_CHANGE")) {
                WifiP2pGroup wifiP2pGroup = (WifiP2pGroup) intent.getParcelableExtra("p2pGroupInfo");
                WifiP2pDevice p2PPrinterInfo = WifiP2pUtils.getInstance(context).getP2PPrinterInfo(wifiP2pGroup);
                EPLog.d(ActivityConnectP2P.TAG, "EXTRA_WIFI_P2P_GROUP = " + wifiP2pGroup);
                if (p2PPrinterInfo != null && p2pConnectConfig.deviceAddress.equals(p2PPrinterInfo.deviceAddress)) {
                    EPLog.d(ActivityConnectP2P.TAG, "P2P Established " + p2PPrinterInfo.deviceName);
                    if (searchWiFiDirectPrinter != null) {
                        searchWiFiDirectPrinter.interrupt();
                        searchWiFiDirectPrinter = null;
                    }
                    ActivityConnectP2P.mHandler.sendEmptyMessage(10);
                }
            }
        }
    }
}
