<commit_before>package io.particle.android.sdk.devicesetup.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AlertDialog.Builder;
import android.view.View;

import com.squareup.phrase.Phrase;

import java.io.IOException;
import java.security.PublicKey;
import java.util.Set;

import io.particle.android.sdk.accountsetup.LoginActivity;
import io.particle.android.sdk.cloud.ParticleCloud;
import io.particle.android.sdk.cloud.ParticleCloudSDK;
import io.particle.android.sdk.devicesetup.ApConnector;
import io.particle.android.sdk.devicesetup.R;
import io.particle.android.sdk.devicesetup.commands.CommandClient;
import io.particle.android.sdk.devicesetup.commands.DeviceIdCommand;
import io.particle.android.sdk.devicesetup.commands.PublicKeyCommand;
import io.particle.android.sdk.devicesetup.commands.SetCommand;
import io.particle.android.sdk.devicesetup.loaders.WifiScanResultLoader;
import io.particle.android.sdk.devicesetup.model.ScanResultNetwork;
import io.particle.android.sdk.devicesetup.setupsteps.SetupStepException;
import io.particle.android.sdk.utils.Crypto;
import io.particle.android.sdk.utils.EZ;
import io.particle.android.sdk.utils.ParticleDeviceSetupInternalStringUtils;
import io.particle.android.sdk.utils.SSID;
import io.particle.android.sdk.utils.SoftAPConfigRemover;
import io.particle.android.sdk.utils.TLog;
import io.particle.android.sdk.utils.WifiFacade;
import io.particle.android.sdk.utils.ui.Ui;
import io.particle.android.sdk.utils.ui.WebViewActivity;

import static io.particle.android.sdk.utils.Py.truthy;


// FIXME: this activity is *far* too complicated.  Split it out into smaller components.
public class DiscoverDeviceActivity extends RequiresWifiScansActivity
        implements WifiListFragment.Client<ScanResultNetwork>, ApConnector.Client {


    // see ApConnector for the timeout value used for connecting to the soft AP
    private static final int MAX_NUM_DISCOVER_PROCESS_ATTEMPTS = 5;

    private static final TLog log = TLog.get(DiscoverDeviceActivity.class);


    private WifiFacade wifiFacade;
    private ParticleCloud sparkCloud;
    private DiscoverProcessWorker discoverProcessWorker;
    private SoftAPConfigRemover softAPConfigRemover;

    private WifiListFragment wifiListFragment;
    private ProgressDialog connectToApSpinnerDialog;

    private AsyncTask<Void, Void, SetupStepException> connectToApTask;
    private boolean isResumed = false;

    private int discoverProcessAttempts = 0;

    private SSID selectedSoftApSSID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discover_device);

        wifiFacade = WifiFacade.get(this);

        softAPConfigRemover = new SoftAPConfigRemover(this);
        softAPConfigRemover.removeAllSoftApConfigs();
        softAPConfigRemover.reenableWifiNetworks();

        DeviceSetupState.previouslyConnectedWifiNetwork = wifiFacade.getCurrentlyConnectedSSID();

        sparkCloud = ParticleCloudSDK.getCloud();

        wifiListFragment = Ui.findFrag(this, R.id.wifi_list_fragment);
        ConnectToApFragment.ensureAttached(this);

        resetWorker();

        Ui.setText(this, R.id.wifi_list_header,
                Phrase.from(this, R.string.wifi_list_header_text)
                        .put("device_name", getString(R.string.device_name))
                        .format()
        );

        Ui.setText(this, R.id.msg_device_not_listed,
                Phrase.from(this, R.string.msg_device_not_listed)
                        .put("device_name", getString(R.string.device_name))
                        .put("setup_button_identifier", getString(R.string.mode_button_name))
                        .put("indicator_light", getString(R.string.indicator_light))
                        .put("indicator_light_setup_color_name", getString(R.string.listen_mode_led_color_name))
                        .format()
        );

        Ui.setTextFromHtml(this, R.id.action_troubleshooting, R.string.troubleshooting).setOnClickListener(
                v -> {
                    Uri uri = Uri.parse(v.getContext().getString(R.string.troubleshooting_uri));
                    startActivity(WebViewActivity.buildIntent(v.getContext(), uri));
                }
        );

        if (!truthy(sparkCloud.getLoggedInUsername())) {
            Ui.findView(this, R.id.logged_in_as).setVisibility(View.GONE);
        } else {
            Ui.setText(this, R.id.logged_in_as,
                    Phrase.from(this, R.string.you_are_logged_in_as)
                            .put("username", sparkCloud.getLoggedInUsername())
                            .format()
            );
        }

        Ui.findView(this, R.id.action_log_out).setOnClickListener(view -> {
            sparkCloud.logOut();
            log.i("logged out, username is: " + sparkCloud.getLoggedInUsername());
            startActivity(new Intent(DiscoverDeviceActivity.this, LoginActivity.class));
            finish();
        });

        Ui.findView(this, R.id.action_cancel).setOnClickListener(view -> finish());
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!wifiFacade.isWifiEnabled()) {
            onWifiDisabled();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        isResumed = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResumed = false;
    }

    private void resetWorker() {
        discoverProcessWorker = new DiscoverProcessWorker(
                CommandClient.newClientUsingDefaultsForDevices(this, selectedSoftApSSID)
        );
    }

    private void onWifiDisabled() {
        log.d("Wi-Fi disabled; prompting user");
        new AlertDialog.Builder(this)
                .setTitle(R.string.wifi_required)
                .setPositiveButton(R.string.enable_wifi, (dialog, which) -> {
                    dialog.dismiss();
                    log.i("Enabling Wi-Fi at the user's request.");
                    wifiFacade.setWifiEnabled(true);
                    wifiListFragment.scanAsync();
                })
                .setNegativeButton(R.string.exit_setup, (dialog, which) -> {
                    dialog.dismiss();
                    finish();
                })
                .show();
    }

    @Override
    public void onNetworkSelected(ScanResultNetwork selectedNetwork) {
        WifiConfiguration wifiConfig = ApConnector.buildUnsecuredConfig(selectedNetwork.getSsid());
        selectedSoftApSSID = selectedNetwork.getSsid();
        connectToSoftAp(wifiConfig);
    }

    private void connectToSoftAp(WifiConfiguration config) {
        discoverProcessAttempts++;
        softAPConfigRemover.onSoftApConfigured(SSID.from(config.SSID));
        ConnectToApFragment.get(this).connectToAP(config);
        showProgressDialog();
    }

    @Override
    public Loader<Set<ScanResultNetwork>> createLoader(int id, Bundle args) {<commit_msg>Reset the worker when we create a new wifi config, since now we'll have to create the CommandClient with the selected soft AP's SSID<commit_after>package io.particle.android.sdk.devicesetup.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AlertDialog.Builder;
import android.view.View;

import com.squareup.phrase.Phrase;

import java.io.IOException;
import java.security.PublicKey;
import java.util.Set;

import io.particle.android.sdk.accountsetup.LoginActivity;
import io.particle.android.sdk.cloud.ParticleCloud;
import io.particle.android.sdk.cloud.ParticleCloudSDK;
import io.particle.android.sdk.devicesetup.ApConnector;
import io.particle.android.sdk.devicesetup.R;
import io.particle.android.sdk.devicesetup.commands.CommandClient;
import io.particle.android.sdk.devicesetup.commands.DeviceIdCommand;
import io.particle.android.sdk.devicesetup.commands.PublicKeyCommand;
import io.particle.android.sdk.devicesetup.commands.SetCommand;
import io.particle.android.sdk.devicesetup.loaders.WifiScanResultLoader;
import io.particle.android.sdk.devicesetup.model.ScanResultNetwork;
import io.particle.android.sdk.devicesetup.setupsteps.SetupStepException;
import io.particle.android.sdk.utils.Crypto;
import io.particle.android.sdk.utils.EZ;
import io.particle.android.sdk.utils.ParticleDeviceSetupInternalStringUtils;
import io.particle.android.sdk.utils.SSID;
import io.particle.android.sdk.utils.SoftAPConfigRemover;
import io.particle.android.sdk.utils.TLog;
import io.particle.android.sdk.utils.WifiFacade;
import io.particle.android.sdk.utils.ui.Ui;
import io.particle.android.sdk.utils.ui.WebViewActivity;

import static io.particle.android.sdk.utils.Py.truthy;


// FIXME: this activity is *far* too complicated.  Split it out into smaller components.
public class DiscoverDeviceActivity extends RequiresWifiScansActivity
        implements WifiListFragment.Client<ScanResultNetwork>, ApConnector.Client {


    // see ApConnector for the timeout value used for connecting to the soft AP
    private static final int MAX_NUM_DISCOVER_PROCESS_ATTEMPTS = 5;

    private static final TLog log = TLog.get(DiscoverDeviceActivity.class);


    private WifiFacade wifiFacade;
    private ParticleCloud sparkCloud;
    private DiscoverProcessWorker discoverProcessWorker;
    private SoftAPConfigRemover softAPConfigRemover;

    private WifiListFragment wifiListFragment;
    private ProgressDialog connectToApSpinnerDialog;

    private AsyncTask<Void, Void, SetupStepException> connectToApTask;
    private boolean isResumed = false;

    private int discoverProcessAttempts = 0;

    private SSID selectedSoftApSSID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discover_device);

        wifiFacade = WifiFacade.get(this);

        softAPConfigRemover = new SoftAPConfigRemover(this);
        softAPConfigRemover.removeAllSoftApConfigs();
        softAPConfigRemover.reenableWifiNetworks();

        DeviceSetupState.previouslyConnectedWifiNetwork = wifiFacade.getCurrentlyConnectedSSID();

        sparkCloud = ParticleCloudSDK.getCloud();

        wifiListFragment = Ui.findFrag(this, R.id.wifi_list_fragment);
        ConnectToApFragment.ensureAttached(this);

        resetWorker();

        Ui.setText(this, R.id.wifi_list_header,
                Phrase.from(this, R.string.wifi_list_header_text)
                        .put("device_name", getString(R.string.device_name))
                        .format()
        );

        Ui.setText(this, R.id.msg_device_not_listed,
                Phrase.from(this, R.string.msg_device_not_listed)
                        .put("device_name", getString(R.string.device_name))
                        .put("setup_button_identifier", getString(R.string.mode_button_name))
                        .put("indicator_light", getString(R.string.indicator_light))
                        .put("indicator_light_setup_color_name", getString(R.string.listen_mode_led_color_name))
                        .format()
        );

        Ui.setTextFromHtml(this, R.id.action_troubleshooting, R.string.troubleshooting).setOnClickListener(
                v -> {
                    Uri uri = Uri.parse(v.getContext().getString(R.string.troubleshooting_uri));
                    startActivity(WebViewActivity.buildIntent(v.getContext(), uri));
                }
        );

        if (!truthy(sparkCloud.getLoggedInUsername())) {
            Ui.findView(this, R.id.logged_in_as).setVisibility(View.GONE);
        } else {
            Ui.setText(this, R.id.logged_in_as,
                    Phrase.from(this, R.string.you_are_logged_in_as)
                            .put("username", sparkCloud.getLoggedInUsername())
                            .format()
            );
        }

        Ui.findView(this, R.id.action_log_out).setOnClickListener(view -> {
            sparkCloud.logOut();
            log.i("logged out, username is: " + sparkCloud.getLoggedInUsername());
            startActivity(new Intent(DiscoverDeviceActivity.this, LoginActivity.class));
            finish();
        });

        Ui.findView(this, R.id.action_cancel).setOnClickListener(view -> finish());
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!wifiFacade.isWifiEnabled()) {
            onWifiDisabled();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        isResumed = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResumed = false;
    }

    private void resetWorker() {
        discoverProcessWorker = new DiscoverProcessWorker(
                CommandClient.newClientUsingDefaultsForDevices(this, selectedSoftApSSID)
        );
    }

    private void onWifiDisabled() {
        log.d("Wi-Fi disabled; prompting user");
        new AlertDialog.Builder(this)
                .setTitle(R.string.wifi_required)
                .setPositiveButton(R.string.enable_wifi, (dialog, which) -> {
                    dialog.dismiss();
                    log.i("Enabling Wi-Fi at the user's request.");
                    wifiFacade.setWifiEnabled(true);
                    wifiListFragment.scanAsync();
                })
                .setNegativeButton(R.string.exit_setup, (dialog, which) -> {
                    dialog.dismiss();
                    finish();
                })
                .show();
    }

    @Override
    public void onNetworkSelected(ScanResultNetwork selectedNetwork) {
        WifiConfiguration wifiConfig = ApConnector.buildUnsecuredConfig(selectedNetwork.getSsid());
        selectedSoftApSSID = selectedNetwork.getSsid();
        resetWorker();
        connectToSoftAp(wifiConfig);
    }

    private void connectToSoftAp(WifiConfiguration config) {
        discoverProcessAttempts++;
        softAPConfigRemover.onSoftApConfigured(SSID.from(config.SSID));
        ConnectToApFragment.get(this).connectToAP(config);
        showProgressDialog();
    }

    @Override
    public Loader<Set<ScanResultNetwork>> createLoader(int id, Bundle args) {
{'fraction_non_alphanumeric': 0.09762748841014453, 'fraction_numerical': 0.0006817562039814562, 'mean_word_length': 2.896148738379814, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6022100', 'n_tokens_mistral': 4329, 'n_tokens_neox': 4093, 'n_words': 660}