package com.tryandroid.battery;

import com.kurukurupapa.tryandroid.fw.MapForListAdapter;
import com.kurukurupapa.tryandroid.fw.MapListForListAdapter;
import com.kurukurupapa.tryandroid.fw.battery.BatteryInfo;
import com.kurukurupapa.tryandroid.fw.util.DateUtil;
import com.kurukurupapa.tryandroid.fw.util.LogUtil;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class BatteryWatchingActivity extends ListActivity {
	private MapListForListAdapter<MapForListAdapter> list;
	private BatteryWatchingBroadcastReceiver receiver;
	private BatteryInfo oldBatteryInfo;

	/*
	 * (非 Javadoc)
	 *
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LogUtil.called();

		receiver = new BatteryWatchingBroadcastReceiver(this);
		list = new MapListForListAdapter<MapForListAdapter>();

		setListAdapter(list.createAdapterAsTwoLine(this));
	}

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

		// バッテリー監視登録
		receiver.register();
	}

	@Override
	protected void onPause() {
		super.onPause();
		LogUtil.called();

		// バッテリー監視解除
		receiver.unregister();
	}

	public void onBatteryChangedReceive(Context context, Intent intent) {
		BatteryInfo batteryInfo = new BatteryInfo(intent);

		StringBuilder sb = new StringBuilder();
		if (oldBatteryInfo != null) {
			if (oldBatteryInfo.present != batteryInfo.present) {
				sb.append("present=" + batteryInfo.present + ", ");
			}
			if (oldBatteryInfo.level != batteryInfo.level) {
				sb.append("level=" + batteryInfo.level + ", ");
			}
			if (oldBatteryInfo.scale != batteryInfo.scale) {
				sb.append("scale=" + batteryInfo.scale + ", ");
			}
			if (oldBatteryInfo.iconSmall != batteryInfo.iconSmall) {
				sb.append("iconSmall=" + batteryInfo.iconSmall + ", ");
			}
			if (oldBatteryInfo.voltage != batteryInfo.voltage) {
				sb.append("voltage=" + batteryInfo.voltage + ", ");
			}
			if (oldBatteryInfo.temperature != batteryInfo.temperature) {
				sb.append("temperature=" + batteryInfo.temperature + ", ");
			}
			if (oldBatteryInfo.status != batteryInfo.status) {
				sb.append("status=" + batteryInfo.status + ", ");
			}
			if (oldBatteryInfo.health != batteryInfo.health) {
				sb.append("health=" + batteryInfo.health + ", ");
			}
			if (oldBatteryInfo.plugged != batteryInfo.plugged) {
				sb.append("plugged=" + batteryInfo.plugged + ", ");
			}
			if (oldBatteryInfo.technology != batteryInfo.technology) {
				sb.append("technology=" + batteryInfo.technology + ", ");
			}
		} else {
			sb.append(batteryInfo.toString());
		}
		oldBatteryInfo = batteryInfo;

		MapForListAdapter map = new MapForListAdapter();
		map.setText1(DateUtil.formatDateTime(batteryInfo.date));
		map.setText2(sb.toString());
		list.add(map);

		setListAdapter(list.createAdapterAsTwoLine(this));
	}
}
