package com.tryandroid.battery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.tryandroid.R;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class BatteryActivity extends Activity {

	private static final String ITEM = "Item";
	private static final String VALUE = "Value";

	private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			BatteryData info = new BatteryData(BatteryActivity.this);
			info.onReceive(context, intent);

			List<Map<String, String>> data = new ArrayList<Map<String, String>>();
			Map<String, String> map = info.getKeyValueMap();
			for (Entry<String, String> e : map.entrySet()) {
				Map<String, String> m = new HashMap<String, String>();
				m.put(ITEM, e.getKey());
				m.put(VALUE, e.getValue());
				data.add(m);
			}

			ListView listView = (ListView) findViewById(R.id.battery_list_view);
			listView.setAdapter(new SimpleAdapter(BatteryActivity.this, data,
					android.R.layout.simple_list_item_2, new String[] { ITEM,
							VALUE }, new int[] { android.R.id.text1,
							android.R.id.text2 }));
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(getClass().getName(), "onCreate Called");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.battery);
	}

	@Override
	protected void onResume() {
		Log.i(getClass().getName(), "onResume Called");
		super.onResume();

		// バッテリー監視登録
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(batteryReceiver, filter);
	}

	@Override
	protected void onPause() {
		Log.i(getClass().getName(), "onPause Called");
		super.onPause();

		// バッテリー監視解除
		unregisterReceiver(batteryReceiver);
	}

}