package com.epson.mobilephone.common.wifidirect;

import android.app.Service;
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.Build;
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 androidx.annotation.RequiresApi;

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

import epson.print.R;

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;
    private 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();
    private 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
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Service.WIFI_SERVICE);
        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);
        toolbar = (ViewGroup) viewGroup.findViewById(R.id.toolbar);
        btnFinish = (Button) viewGroup.findViewById(R.id.btn_finish);
        textView1 = (TextView) viewGroup.findViewById(R.id.textView1);
        textView2 = (TextView) viewGroup.findViewById(R.id.textView2);
        textView3 = (TextView) viewGroup.findViewById(R.id.textView3);
        progress = (ProgressBar) viewGroup.findViewById(R.id.progressBarGetConnectStrings);
        btnFinish.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onFinishPressed();
            }
        });
        mEscprLib.epsWrapperGetSetupConnectStrings(settingsTempAp);
    }

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

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

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

    protected void onResume() {
        super.onResume();
        isKeepSimpleAPConnection = false;
        switch (status) {
            case IDLE:
                setDisplayMenu(false);
                toolbar.setVisibility(View.GONE);
                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.d(TAG, "onPause()");
        super.onPause();
        if (status == Status.GETTING_GONNECTSTRINGS) {
            EPLog.d(TAG, "interruputGetConnectSttings()");
            status = Status.CONNECT_ERROR;
            AsyncTask<Void, Void, Boolean> asyncTask = taskGetConnectStrings;
            if (asyncTask != null) {
                asyncTask.cancel(true);
                taskGetConnectStrings = null;
            }
        }
        WiFiUtils wiFiUtils2 = wiFiUtils;
        wiFiUtils2.removeSimpleAP(wiFiUtils2.getNetworkId(settingsTempAp.ssid));
        if (!isKeepSimpleAPConnection && settingsRealAp.ssid != null) {
            disconnectRealAp();
        }
    }

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

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

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

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

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

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

    private void startConnectTempAp() {
        EPLog.d(TAG, "startConnectTempAp()");
        Intent intent = new Intent(this, ActivityConnectSimpleAP.class);
        intent.putExtra(ActivityConnectBase.APNAME, settingsTempAp.ssid);
        intent.putExtra(ActivityConnectBase.APPASS, 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.d(TAG, "startConnectRealAp()");
        taskGetConnectStrings = new AsyncTask<Void, Void, Boolean>() {
            protected void onPreExecute() {
                getWindow().addFlags(128);
                Status unused = status = Status.GETTING_GONNECTSTRINGS;
            }

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

            protected void onPostExecute(Boolean bool) {
                getWindow().clearFlags(128);
                if (bool.booleanValue()) {
                    Status unused = status = Status.CONNECTING_REALAP;
                    Intent intent = new Intent(this, ActivityConnectSimpleAP.class);
                    intent.putExtra(ActivityConnectBase.APNAME, settingsRealAp.ssid);
                    intent.putExtra(ActivityConnectBase.APPASS, 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);
                    startActivityForResult(intent, 2);
                    return;
                }
                Status unused2 = status = Status.CONNECT_ERROR;
                onConnectError();
            }

            protected void onCancelled() {
                EPLog.d(TAG, "taskGetConnectStrings Canceled");
                Status unused = status = Status.CONNECT_ERROR;
                getWindow().clearFlags(128);
                wiFiUtils.removeSimpleAP(wiFiUtils.getNetworkId(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 = mWifiManager.getConnectionInfo().getMacAddress();
        if (macAddress != null) {
            EPLog.d(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 = mWifiManager.getScanResults();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        if (arrayList.size() != 0) {
            for (ScanResult scanResult : arrayList) {
                if (settingsRealAp.ssid.equals(WiFiUtils.removeQuotationsInSSID(scanResult.SSID))) {
                    EPLog.d(TAG, "Found AP");
                    synchronized (waitRealAp) {
                        waitRealAp.notify();
                    }
                    return;
                }
            }
        }
        new WiFiScanner().startScan(mWifiManager);
    }

    class NetworkStateChangeReciever extends BroadcastReceiver {
        NetworkStateChangeReciever() {
        }

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