package com.kurukurupapa.tryandroid.fw.battery;

import com.kurukurupapa.tryandroid.fw.util.LogUtil;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class BatteryChangedReceiver extends BroadcastReceiver {
	public interface OnBatteryChangedListener {
		public void onBatteryChangedReceive(Context context, Intent intent,
				BatteryInfo batteryInfo);
	}

	protected Context context;
	protected OnBatteryChangedListener listener;

	public BatteryChangedReceiver(Context context,
			OnBatteryChangedListener listener) {
		this.context = context;
		this.listener = listener;
	}

	public void register() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_BATTERY_CHANGED);
		context.registerReceiver(this, filter);
		LogUtil.i("Registered battery receiver");
	}

	public void unregister() {
		context.unregisterReceiver(this);
		LogUtil.i("Unregistered battery receiver");
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		if (!intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
			return;
		}
		LogUtil.called();

		// バッテリー状態測定
		BatteryInfo batteryInfo = new BatteryInfo(intent);

		LogUtil.i("Battery: " + batteryInfo.getPercentageString() + ", "
				+ batteryInfo.getStatusString());

		// リスナー処理の呼び出し
		listener.onBatteryChangedReceive(context, intent, batteryInfo);
	}

}
