package com.epson.mobilephone.common.wifidirect;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.epson.mobilephone.common.wifidirect.escprLib;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ActivityiPrintConnect extends ActivityWiFiDirectBase {
    public static final String FINISH_EAYSETUP = "easysetup";
    private static final int MACADRESS_SIZE = 6;
    private static final int MAX_RETRY = 5;
    private static final int RUNDOM_SIZE = 4;
    private static final String TAG = "ActivityiPrintConnect";
    private static final int TIMEOUT_CONNECTING_REALAP = 60;
    private static final int TIMEOUT_CONNECTING_TESTAP = 60;
    private static final int WAIT_CONNECTREALAP = 120;
    private static final int WAIT_RETRY = 2;
    /* access modifiers changed from: private */
    public static byte[] engineId;
    private final int CONNECT_REALAP = 2;
    private final int CONNECT_TESTAP = 1;
    Button btnFinish;
    Intent intentResult = null;
    boolean isKeepSimpleAPConnection = false;
    String lastErrorStrings = "";
    escprLib mEscprLib = new escprLib();
    WifiManager mWifiManager = null;
    NetworkStateChangeReciever networkStateChangeReciever = null;
    ProgressBar progress;
    escprLib.ConnectStrings settingsRealAp = new escprLib.ConnectStrings();
    escprLib.ConnectStrings settingsTempAp = new escprLib.ConnectStrings();
    /* access modifiers changed from: private */
    public Status status = Status.IDLE;
    AsyncTask<Void, Void, Boolean> taskGetConnectStrings = null;
    TextView textView1;
    TextView textView2;
    TextView textView3;
    ViewGroup toolbar;
    Object waitRealAp = new Object();
    WiFiUtils wiFiUtils = null;

    enum Status {
        IDLE,
        CONNECTING_TEMPAP,
        GETTING_GONNECTSTRINGS,
        CONNECTING_REALAP,
        CONNECTED,
        CONNECTED_OTHERAP,
        CONNECT_ERROR
    }

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        this.mWifiManager = (WifiManager) getApplicationContext().getSystemService("wifi");
        this.wiFiUtils = WiFiUtils.getInstance(this);
        if (engineId == null) {
            engineId = getEngineId();
        }
        ViewGroup viewGroup = (ViewGroup) getLayoutInflater().inflate(R.layout.iprintconnect, (ViewGroup) null);
        setContentView((View) viewGroup);
        setupCommonHeaderControl(false, false);
        this.toolbar = (ViewGroup) viewGroup.findViewById(R.id.toolbar);
        this.btnFinish = (Button) viewGroup.findViewById(R.id.btn_finish);
        this.textView1 = (TextView) viewGroup.findViewById(R.id.textView1);
        this.textView2 = (TextView) viewGroup.findViewById(R.id.textView2);
        this.textView3 = (TextView) viewGroup.findViewById(R.id.textView3);
        this.progress = (ProgressBar) viewGroup.findViewById(R.id.progressBarGetConnectStrings);
        this.btnFinish.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                ActivityiPrintConnect.this.onFinishPressed();
            }
        });
        this.mEscprLib.epsWrapperGetSetupConnectStrings(this.settingsTempAp);
    }

    public void onFinishPressed() {
        Intent intent = this.intentResult;
        if (intent != null) {
            setResult(-1, intent);
            this.isKeepSimpleAPConnection = true;
        } else {
            setResult(0);
        }
        finish();
    }

    public void onCancelPressed() {
        super.onCancelPressed();
        disconnectRealAp();
    }

    private void disconnectRealAp() {
        this.status = Status.CONNECT_ERROR;
        WiFiUtils wiFiUtils2 = this.wiFiUtils;
        wiFiUtils2.removeSimpleAP(wiFiUtils2.getNetworkId(this.settingsRealAp.ssid));
    }

    protected void onResume() {
        super.onResume();
        this.isKeepSimpleAPConnection = false;
        switch (this.status) {
            case IDLE:
                setDisplayMenu(false);
                this.toolbar.setVisibility(8);
                this.status = Status.CONNECTING_TEMPAP;
                startConnectTempAp();
                return;
            case CONNECTED:
                onConnectSimpleAP();
                return;
            case CONNECTED_OTHERAP:
                onConnectOtherAP();
                return;
            case CONNECT_ERROR:
                onConnectError();
                return;
            default:
                return;
        }
    }

    protected void onPause() {
        EPLog.m86d(TAG, "onPause()");
        super.onPause();
        if (this.status == Status.GETTING_GONNECTSTRINGS) {
            EPLog.m86d(TAG, "interruputGetConnectSttings()");
            this.status = Status.CONNECT_ERROR;
            AsyncTask<Void, Void, Boolean> asyncTask = this.taskGetConnectStrings;
            if (asyncTask != null) {
                asyncTask.cancel(true);
                this.taskGetConnectStrings = null;
            }
        }
        WiFiUtils wiFiUtils2 = this.wiFiUtils;
        wiFiUtils2.removeSimpleAP(wiFiUtils2.getNetworkId(this.settingsTempAp.ssid));
        if (!this.isKeepSimpleAPConnection && this.settingsRealAp.ssid != null) {
            disconnectRealAp();
        }
    }

    private void registBroadcastReciever() {
        if (this.networkStateChangeReciever == null) {
            this.networkStateChangeReciever = new NetworkStateChangeReciever();
            registerReceiver(this.networkStateChangeReciever, new IntentFilter("android.net.wifi.SCAN_RESULTS"));
        }
    }

    private void unRegistBroadcastReciever() {
        NetworkStateChangeReciever networkStateChangeReciever2 = this.networkStateChangeReciever;
        if (networkStateChangeReciever2 != null) {
            unregisterReceiver(networkStateChangeReciever2);
            this.networkStateChangeReciever = null;
        }
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        String ssid = this.wiFiUtils.getSSID(this.wiFiUtils.getCurNetworkId());
        switch (i) {
            case 1:
                if (i2 != -1) {
                    this.status = Status.CONNECT_ERROR;
                    return;
                } else if (this.settingsTempAp.ssid.equals(ssid)) {
                    startConnectRealAp();
                    return;
                } else if (ssid != null) {
                    this.status = Status.CONNECTED_OTHERAP;
                    return;
                } else {
                    this.status = Status.CONNECT_ERROR;
                    return;
                }
            case 2:
                if (i2 != -1) {
                    this.status = Status.CONNECT_ERROR;
                    return;
                } else if (this.settingsRealAp.ssid.equals(ssid)) {
                    this.intentResult = intent;
                    this.intentResult.putExtra(FINISH_EAYSETUP, true);
                    this.status = Status.CONNECTED;
                    return;
                } else if (ssid != null) {
                    this.status = Status.CONNECTED_OTHERAP;
                    return;
                } else {
                    this.status = Status.CONNECT_ERROR;
                    return;
                }
            default:
                return;
        }
    }

    private void onConnectSimpleAP() {
        EPLog.m86d(TAG, "onConnectSimpleAP()");
        this.toolbar.setVisibility(0);
        this.progress.setVisibility(8);
        setDisplayMenu(true);
        this.textView1.setText(getResources().getString(R.string.str_connected_printer1));
        TextView textView = this.textView2;
        Resources resources = getResources();
        WiFiUtils wiFiUtils2 = this.wiFiUtils;
        textView.setText(resources.getString(R.string.str_connected_printer2, new Object[]{this.intentResult.getStringExtra("name"), wiFiUtils2.getSSID(wiFiUtils2.getCurNetworkId())}));
        this.textView3.setText(getResources().getString(R.string.str_connected_printer3));
    }

    private void onConnectOtherAP() {
        EPLog.m86d(TAG, "onConnectOtherAP()");
        this.toolbar.setVisibility(8);
        this.progress.setVisibility(8);
        setDisplayMenu(true);
        this.textView1.setText(getResources().getString(R.string.str_connected_otherAP1));
        this.textView2.setText(getResources().getString(R.string.str_connected_otherAP2));
        this.textView3.setText(getResources().getString(R.string.str_connected_otherAP3));
    }

    private void onConnectError() {
        EPLog.m86d(TAG, "onConnectError()");
        this.toolbar.setVisibility(8);
        this.progress.setVisibility(8);
        setDisplayMenu(true);
        this.textView1.setText(getResources().getString(R.string.str_connect_error1));
        this.textView2.setText(getResources().getString(R.string.str_connect_error2));
        this.textView3.setText(getResources().getString(R.string.str_connect_error3));
    }

    private void startConnectTempAp() {
        EPLog.m86d(TAG, "startConnectTempAp()");
        Intent intent = new Intent(this, ActivityConnectSimpleAP.class);
        intent.putExtra(ActivityConnectBase.APNAME, this.settingsTempAp.ssid);
        intent.putExtra(ActivityConnectBase.APPASS, this.settingsTempAp.password);
        intent.putExtra(ActivityConnectBase.CREATE, true);
        intent.putExtra(ActivityConnectBase.SHOWERROR, false);
        intent.putExtra(ActivityConnectBase.SHOWTIP, false);
        intent.putExtra(ActivityConnectBase.TIMEOUT, 60);
        intent.putExtra(ActivityConnectBase.NEEDINFO, false);
        startActivityForResult(intent, 1);
    }

    private void startConnectRealAp() {
        EPLog.m86d(TAG, "startConnectRealAp()");
        this.taskGetConnectStrings = new AsyncTask<Void, Void, Boolean>() {
            protected void onPreExecute() {
                ActivityiPrintConnect.this.getWindow().addFlags(128);
                Status unused = ActivityiPrintConnect.this.status = Status.GETTING_GONNECTSTRINGS;
            }

            protected Boolean doInBackground(Void... voidArr) {
                ActivityiPrintConnect.this.wiFiUtils.pingWiFiDirectPrinter();
                ActivityiPrintConnect.this.mEscprLib.epsWrapperInitDriver(192);
                boolean z = false;
                int i = -1;
                int i2 = 0;
                int i3 = -1;
                while (i2 < 5) {
                    try {
                        if (!isCancelled()) {
                            i3 = ActivityiPrintConnect.this.mEscprLib.epsWrapperGetConnectStrings(ActivityiPrintConnect.engineId, ActivityiPrintConnect.this.settingsRealAp);
                            if (!isCancelled()) {
                                if (i3 == 0) {
                                    break;
                                }
                                i2++;
                                EPLog.m88i(ActivityiPrintConnect.TAG, "epsWrapperGetConnectStrings ret = " + i3 + " retry = " + i2);
                                Thread.sleep(2000);
                            } else {
                                throw new InterruptedException();
                            }
                        } else {
                            throw new InterruptedException();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (i3 == 0) {
                    EPLog.m86d(ActivityiPrintConnect.TAG, "epsWrapperGetConnectStrings ssid = " + ActivityiPrintConnect.this.settingsRealAp.ssid + " printerId = " + ActivityiPrintConnect.this.settingsRealAp.printerId);
                    ActivityiPrintConnect.this.mEscprLib.epsWrapperStartWifiDirect(ActivityiPrintConnect.this.settingsRealAp.printerIp.toCharArray());
                    synchronized (ActivityiPrintConnect.this.waitRealAp) {
                        ActivityiPrintConnect.this.registBroadcastReciever();
                        ActivityiPrintConnect.this.mWifiManager.startScan();
                        long currentTimeMillis = System.currentTimeMillis();
                        ActivityiPrintConnect.this.waitRealAp.wait(120000);
                        if (System.currentTimeMillis() - currentTimeMillis >= 120000) {
                            EPLog.m87e(ActivityiPrintConnect.TAG, "Find RealAp Timepout");
                            i3 = -1;
                        }
                    }
                } else {
                    EPLog.m87e(ActivityiPrintConnect.TAG, "epsWrapperGetConnectStrings ret = " + i3);
                    ActivityiPrintConnect activityiPrintConnect = ActivityiPrintConnect.this;
                    activityiPrintConnect.lastErrorStrings = "epsWrapperGetConnectStrings ret = " + i3;
                }
                ActivityiPrintConnect.this.wiFiUtils.removeSimpleAP(ActivityiPrintConnect.this.wiFiUtils.getNetworkId(ActivityiPrintConnect.this.settingsTempAp.ssid));
                i = i3;
                ActivityiPrintConnect.this.unRegistBroadcastReciever();
                ActivityiPrintConnect.this.mEscprLib.epsWrapperReleaseDriver();
                if (i == 0) {
                    z = true;
                }
                return Boolean.valueOf(z);
            }

            protected void onPostExecute(Boolean bool) {
                ActivityiPrintConnect.this.getWindow().clearFlags(128);
                if (bool.booleanValue()) {
                    Status unused = ActivityiPrintConnect.this.status = Status.CONNECTING_REALAP;
                    Intent intent = new Intent(ActivityiPrintConnect.this, ActivityConnectSimpleAP.class);
                    intent.putExtra(ActivityConnectBase.APNAME, ActivityiPrintConnect.this.settingsRealAp.ssid);
                    intent.putExtra(ActivityConnectBase.APPASS, ActivityiPrintConnect.this.settingsRealAp.password);
                    intent.putExtra(ActivityConnectBase.CREATE, true);
                    intent.putExtra(ActivityConnectBase.SHOWERROR, false);
                    intent.putExtra(ActivityConnectBase.SHOWTIP, false);
                    intent.putExtra(ActivityConnectBase.TIMEOUT, 60);
                    intent.putExtra(ActivityConnectBase.NEEDINFO, true);
                    ActivityiPrintConnect.this.startActivityForResult(intent, 2);
                    return;
                }
                Status unused2 = ActivityiPrintConnect.this.status = Status.CONNECT_ERROR;
                ActivityiPrintConnect.this.onConnectError();
            }

            protected void onCancelled() {
                EPLog.m86d(ActivityiPrintConnect.TAG, "taskGetConnectStrings Canceled");
                Status unused = ActivityiPrintConnect.this.status = Status.CONNECT_ERROR;
                ActivityiPrintConnect.this.getWindow().clearFlags(128);
                ActivityiPrintConnect.this.wiFiUtils.removeSimpleAP(ActivityiPrintConnect.this.wiFiUtils.getNetworkId(ActivityiPrintConnect.this.settingsTempAp.ssid));
                super.onCancelled();
            }
        }.execute(new Void[0]);
    }

    private byte[] getEngineId() {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(10);
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            byteArrayOutputStream.write(random.nextInt());
        }
        String macAddress = this.mWifiManager.getConnectionInfo().getMacAddress();
        if (macAddress != null) {
            EPLog.m86d(TAG, "getEngineId macAdress = " + macAddress);
            String[] split = macAddress.split(":", 6);
            if (split.length == 6) {
                for (int i2 = 0; i2 < 6; i2++) {
                    byteArrayOutputStream.write((byte) Integer.parseInt(split[i2], 16));
                }
            }
        } else {
            byteArrayOutputStream.write(new byte[]{0, 0, 0, 0, 0, 0}, 0, 6);
        }
        return byteArrayOutputStream.toByteArray();
    }

    private void onScanResultAvailable() {
        List<ScanResult> arrayList = new ArrayList<>();
        try {
            arrayList = this.mWifiManager.getScanResults();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        if (arrayList.size() != 0) {
            for (ScanResult scanResult : arrayList) {
                if (this.settingsRealAp.ssid.equals(WiFiUtils.removeQuotationsInSSID(scanResult.SSID))) {
                    EPLog.m86d(TAG, "Found AP");
                    synchronized (this.waitRealAp) {
                        this.waitRealAp.notify();
                    }
                    return;
                }
            }
        }
        new WiFiScanner().startScan(this.mWifiManager);
    }

    class NetworkStateChangeReciever extends BroadcastReceiver {
        NetworkStateChangeReciever() {
        }

        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.net.wifi.SCAN_RESULTS")) {
                EPLog.m86d(ActivityiPrintConnect.TAG, "Scan Results Available");
                ActivityiPrintConnect.this.onScanResultAvailable();
            }
        }
    }
}
