package com.epson.mobilephone.common.wifidirect;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
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.DialogFragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import java.util.Deque;

import epson.print.R;
import epson.print.Util.EPLog;

public class ActivityConnectSimpleAP extends ActivityConnectBase implements DialogProgressWiFiDirect.DialogButtonClick {
    private static final int DELAY_CONNECTED_WIFI = 1000;
    private static final String IDD_WIFI_ERROR = "idd_wifi_error";
    private static final String IDD_WIFI_PROFILE_FAILED = "idd_wifi_profile_failed";
    private static final String IDD_WIFI_SIMPLEAP = "idd_wifi_simpleap";
    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_FOUND = 1;
    private static final int ID_NOT_FOUND = 2;
    private static final int ID_RESULT = 0;
    private static final int MAX_RETRY_CONNECTING = 5;
    private static final String TAG = "ActivityConnectSimpleAP";
    private int connectingNetworkId = -1;
    boolean createSimpleAP = false;

    Handler mHandler = new Handler() {
        public void handleMessage(Message message) {
            super.handleMessage(message);
            switch (C10874.f150x55760faf[status.ordinal()]) {
                case 1:
                    if (message.what == 11) {
                        if (Build.VERSION.SDK_INT > 25 && !createSimpleAP) {
                            mModelDialog.doShow(IDD_WIFI_SIMPLEAP);
                            return;
                        } else if (!mWifiManager.isWifiEnabled()) {
                            startActivityForResult(new Intent(ActivityConnectSimpleAP.this, ActivityControlWiFi.class), 1);
                            return;
                        } else {
                            onEnabledWifi();
                            return;
                        }
                    } else {
                        return;
                    }
                case 2:
                    if (message.what == 0) {
                        Bundle data = message.getData();
                        if (data != null && !data.isEmpty()) {
                            String removeSSIDPrefix = WiFiControl.removeSSIDPrefix(data.getString("ssid"));
                            if (targetSsid.equals(removeSSIDPrefix)) {
                                if (searchWiFiDirectPrinter != null) {
                                    searchWiFiDirectPrinter.interrupt();
                                    searchWiFiDirectPrinter = null;
                                }
                                int unused = connectingNetworkId = data.getInt("id");
                                if (WiFiUtils.getInstance(ActivityConnectSimpleAP.this).enableSimpleAP(connectingNetworkId, removeSSIDPrefix)) {
                                    status = ActivityConnectBase.Status.WIFI_CONNECTING;
                                    setupObserver();
                                    break;
                                } else {
                                    onError();
                                    break;
                                }
                            }
                        } else {
                            EPLog.e(TAG, "Not Found Network");
                            status = ActivityConnectBase.Status.IDLE;
                            onError();
                            break;
                        }
                    }
                    break;
                case 3:
                    break;
                case 4:
                    switch (message.what) {
                        case 1:
                            Bundle data2 = message.getData();
                            if (data2 != null) {
                                String string = data2.getString("name");
                                String string2 = data2.getString(escprLib.PRINTER_IP);
                                String string3 = data2.getString("id");
                                if (string != null && string2 != null && string3 != null) {
                                    EPLog.i(TAG, "epsWrapperFindPrinter Success");
                                    if (!expectedPrtMacAddr.equals(MacAddrUtils.getMacAddressFromPrinterId(string3))) {
                                        EPLog.i(TAG, "This Printer is not expected " + string);
                                        return;
                                    }
                                    interruptFindingPrinter();
                                    Intent intent = new Intent();
                                    intent.putExtras(data2);
                                    onConnectedPrinter(intent);
                                    return;
                                }
                                return;
                            }
                            return;
                        case 2:
                            onError();
                            return;
                        default:
                            return;
                    }
                default:
                    return;
            }
            if (message.what == 10) {
                status = ActivityConnectBase.Status.WIFI_CONNECTED;
                onConnectedWiFi();
            }
        }
    };
    private DialogProgressWiFiDirectViewModel mModelDialog;
    NetworkStateChangeReciever networkStateChangeReciever = null;
    private int retryConnecting = 0;
    String targetPass = "";

    public void onCancelDialog(String str) {
    }

    public void onNeutralClick(String str) {
    }

    static /* synthetic */ int access(ActivityConnectSimpleAP activityConnectSimpleAP) {
        int i = retryConnecting;
        retryConnecting = i + 1;
        return i;
    }

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        mModelDialog = (DialogProgressWiFiDirectViewModel) ViewModelProviders.of(ActivityConnectSimpleAP.this).get(DialogProgressWiFiDirectViewModel.class);
        mModelDialog.getDialogJob().observe(this, new Observer<Deque<String[]>>() {
            public void onChanged(@Nullable Deque<String[]> deque) {
                String[] checkQueue = 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);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            targetSsid = extras.getString(ActivityConnectBase.APNAME);
            targetPass = extras.getString(ActivityConnectBase.APPASS);
            showErrorDlg = extras.getBoolean(ActivityConnectBase.SHOWERROR, false);
            showConnectedTip = extras.getBoolean(ActivityConnectBase.SHOWTIP, true);
            createSimpleAP = extras.getBoolean(ActivityConnectBase.CREATE, false);
            needInfo = extras.getBoolean(ActivityConnectBase.NEEDINFO, false);
            timeout = extras.getInt(ActivityConnectBase.TIMEOUT, 30);
        }
        EPLog.i(TAG, "Starting connect :" + targetSsid + " timeout = " + timeout);
        mHandler.sendEmptyMessage(11);
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i != 2) {
            switch (i) {
                case 4:
                    if (targetSsid.equals(WiFiUtils.getInstance(this).getCurSSID())) {
                        onConnectedWiFi();
                        return;
                    }
                    setResult(0);
                    setLastDetailResult(2);
                    finish();
                    return;
                case 5:
                    onEnabledWifi();
                    return;
                default:
                    return;
            }
        } else if (i2 != -1) {
            closeWaitingDialog();
            setResult(0);
            setLastDetailResult(1);
            finish();
        } else if (!searchWiFiDirectPrinter.start(1, mHandler, 0, timeout)) {
            onError();
        } else {
            status = ActivityConnectBase.Status.WIFI_SCANNING;
        }
    }

    protected void onEnabledWifi() {
        if (targetSsid.equals(WiFiUtils.getInstance(this).getCurSSID())) {
            EPLog.d(TAG, "Already Connected!!");
            status = ActivityConnectBase.Status.WIFI_CONNECTING;
            mHandler.sendEmptyMessage(10);
            return;
        }
        if (WifiP2pUtils.getInstance(this).isConnectedWiFiP2P()) {
            WifiP2pUtils.getInstance(this).disconnect();
        }
        if (createSimpleAP) {
            connectingNetworkId = WiFiUtils.getInstance(this).createSimpleAP(targetSsid, targetPass);
            if (connectingNetworkId == -1) {
                mModelDialog.doShow(IDD_WIFI_PROFILE_FAILED);
                return;
            }
            status = ActivityConnectBase.Status.WIFI_CONNECTING;
            setupObserver();
            return;
        }
        ActivityRequestLocationPermission.requestLocationPermissionForce(this, 2);
    }


    public void showDialog(java.lang.String r11) {

        throw new UnsupportedOperationException("Method not decompiled: com.epson.mobilephone.common.wifidirect.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();
        NetworkStateChangeReciever networkStateChangeReciever2 = networkStateChangeReciever;
        if (networkStateChangeReciever2 != null) {
            try {
                unregisterReceiver(networkStateChangeReciever2);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            networkStateChangeReciever = null;
        }
    }

    private void onConnectedWiFi() {
        EPLog.d(TAG, "onConnect()");
        interruptConnecting();
        new AsyncTask<Void, Void, Void>() {
            protected Void doInBackground(Void... voidArr) {
                WiFiUtils.getInstance(ActivityConnectSimpleAP.this).waitConnected();
                return null;
            }

            protected void onPostExecute(Void voidR) {
                ManageDefaultNetwork.getInstance(ActivityConnectSimpleAP.this).setDefaultNetworkSimpleAp();
                if (showConnectedTip) {
                    ActivityConnectSimpleAP activityConnectSimpleAP = ActivityConnectSimpleAP.this;
                    Toast.makeText(activityConnectSimpleAP, getString(R.string.str_notice_wifi_connected), 0).show();
                }
                if (!needInfo) {
                    closeWaitingDialog();
                    status = ActivityConnectBase.Status.IDLE;
                    setResult(-1);
                    ActivityConnectBase.setLastDetailResult(-1);
                    finish();
                    return;
                }
                if (taskFindPrinter != null) {
                    EPLog.w(TAG, "Already called onConnect()");
                }
                String curP2PMacAdder = WiFiUtils.getInstance(ActivityConnectSimpleAP.this).getCurP2PMacAdder();
                expectedPrtMacAddr = WiFiControl.p2pAddr2PtrAddrP2P(curP2PMacAdder, (String) null);
                status = ActivityConnectBase.Status.PRINTER_FINDING;
                ActivityConnectSimpleAP activityConnectSimpleAP2 = ActivityConnectSimpleAP.this;
                activityConnectSimpleAP2.taskFindPrinter = new FindPrinterTask(activityConnectSimpleAP2.mHandler, timeout, 1, 2);
                taskFindPrinter.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]);
            }
        }.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;
        }
        if (status == ActivityConnectBase.Status.WIFI_CONNECTING && connectingNetworkId != -1) {
            interruptConnecting();
            WiFiUtils.getInstance(this).removeNetwork(connectingNetworkId);
            connectingNetworkId = -1;
            WiFiUtils.getInstance(this).reConnectNetwork();
            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_WATING already closed");
        }
    }

    /* renamed from: com.epson.mobilephone.common.wifidirect.ActivityConnectSimpleAP$4 */
    static /* synthetic */ class C10874 {

        /* renamed from: $SwitchMap$com$epson$mobilephone$common$wifidirect$ActivityConnectBase$Status */
        static final /* synthetic */ int[] f150x55760faf = new int[ActivityConnectBase.Status.values().length];
    }

    public void setupObserver() {
        super.setupObserver();
        networkStateChangeReciever = new NetworkStateChangeReciever();
        registerReceiver(networkStateChangeReciever, new IntentFilter("android.net.wifi.STATE_CHANGE"));
        registerReceiver(networkStateChangeReciever, new IntentFilter("android.net.wifi.WIFI_STATE_CHANGED"));
        registerReceiver(networkStateChangeReciever, new IntentFilter("android.net.wifi.supplicant.STATE_CHANGE"));
    }


    public void onPositiveClick(java.lang.String r5) {

        throw new UnsupportedOperationException("Method not decompiled: com.epson.mobilephone.common.wifidirect.onPositiveClick(java.lang.String):void");
    }

    public void onNegativeClick(java.lang.String r5) {

        throw new UnsupportedOperationException("Method not decompiled: com.epson.mobilephone.common.wifidirect.onNegativeClick(java.lang.String):void");
    }

    class NetworkStateChangeReciever extends BroadcastReceiver {
        NetworkStateChangeReciever() {
        }

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("android.net.wifi.WIFI_STATE_CHANGED")) {
                EPLog.d(TAG, String.format("WiFi State Change : wifiState = %d", new Object[]{Integer.valueOf(intent.getIntExtra("wifi_state", 4))}));
            } else if (action.equals("android.net.wifi.STATE_CHANGE")) {
                NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra("networkInfo");
                EPLog.d(TAG, "Network State Changed:" + networkInfo.toString());
                if (networkInfo.isConnected() && targetSsid.equals(WiFiUtils.getInstance(this).getCurSSID())) {
                    EPLog.i(TAG, "Wi-Fi connected.");
                    mHandler.sendEmptyMessageDelayed(10, 1000);
                }
            } else if (action.equals("android.net.wifi.supplicant.STATE_CHANGE")) {
                SupplicantState supplicantState = (SupplicantState) intent.getParcelableExtra("newState");
                EPLog.d(TAG, "Supplicant State Changed: State = " + supplicantState.toString());
                if (intent.hasExtra("supplicantError")) {
                    Integer valueOf = Integer.valueOf(intent.getIntExtra("supplicantError", 0));
                    EPLog.d(TAG, "Supplicant State Changed: ErrorCode = " + valueOf.toString());
                    if (status == ActivityConnectBase.Status.WIFI_CONNECTING) {
                        EPLog.d(TAG, "EXTRA_SUPPLICANT_ERROR");
                        onError();
                        return;
                    }
                }
                if (supplicantState == SupplicantState.ASSOCIATING && status == ActivityConnectBase.Status.WIFI_CONNECTING) {
                    access(ActivityConnectSimpleAP.this);
                    if (retryConnecting > 5) {
                        EPLog.d(TAG, "Connecting Retry timeout");
                        onError();
                    }
                }
            }
        }
    }
}
