package com.example.hello.android.wifi_state_receiver;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity
{

	private static final String LOG_TAG = "XXX";
	private WifiStateTextUpdater wifiStateTextUpdater;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		this.wifiStateTextUpdater = new WifiStateTextUpdater();
		updateWifiStateText();
	}

	@Override
	protected void onResume()
	{
		super.onResume();

		// Register wifiStateTextUpdater
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		registerReceiver(wifiStateTextUpdater, intentFilter);
	}

	@Override
	protected void onPause()
	{
		// Unregister wifiStateTextUpdater
		unregisterReceiver(wifiStateTextUpdater);

		super.onPause();
	}

	private void updateWifiStateText()
	{
		WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		int wifiState = wifiManager.getWifiState();
		updateWifiStateText(wifiState);
	}

	private void updateWifiStateText(int wifiState)
	{
		String wifiStateString = null;
		switch (wifiState)
		{
			case WifiManager.WIFI_STATE_DISABLED:
				wifiStateString = "WIFI_STATE_DISABLED";
				break;
			case WifiManager.WIFI_STATE_DISABLING:
				wifiStateString = "WIFI_STATE_DISABLING";
				break;
			case WifiManager.WIFI_STATE_ENABLED:
				wifiStateString = "WIFI_STATE_ENABLED";
				break;
			case WifiManager.WIFI_STATE_ENABLING:
				wifiStateString = "WIFI_STATE_ENABLING";
				break;
			case WifiManager.WIFI_STATE_UNKNOWN:
				wifiStateString = "WIFI_STATE_UNKNOWN";
				break;
		}

		TextView wifiStateTextView = (TextView) findViewById(R.id.wifi_state_text);
		wifiStateTextView.setText(wifiStateString);
	}

	class WifiStateTextUpdater extends BroadcastReceiver
	{

		@Override
		public void onReceive(Context cntxt, Intent intent)
		{
			Log.d(LOG_TAG, "WifiStateTextUpdater#onReceive() : Hello");

			Bundle extras = intent.getExtras();
			if (extras != null)
			{
				int wifiState = extras.getInt(WifiManager.EXTRA_WIFI_STATE);
				Log.d(LOG_TAG, "WifiStateTextUpdater#onReceive() : wifiState => " + wifiState);
				updateWifiStateText(wifiState);
			}

			Log.d(LOG_TAG, "WifiStateTextUpdater#onReceive() : Bye");
		}
	}
}
