package devices;


import anywheresoftware.b4a.BA;

@BA.ShortName("WindowsBattery")
@BA.Events(values={
		"batterychanged (Level As Int, Plugged As Boolean)",
		"log(msg As String)"
		})
public class WindowsBattery {
	private BA ba;
	private String event;
	private Object me;
	private boolean isInitialized = false;
	private boolean need_log_event = false;
	private boolean need_batterychanged_event = false;
	
	
	public void Initialize(BA ba, String EventName) {
		this.ba = ba;
		this.event = EventName.toLowerCase();
		me = this;
		check_events();
		isInitialized = true;
		
	}
	
	private void check_events() {
		if (ba!=null) {
			if (event!=null && event.length()>0) {
				need_log_event = ba.subExists(event + "_log");
				need_batterychanged_event = ba.subExists(event + "_batterychanged");
			}
		}
	}
	
	public boolean IsInitialized() {
		return isInitialized;
	}
	
	public boolean CheckStatus() {
		if (!isInitialized) {
			return false;
		}
		Kernel32.SYSTEM_POWER_STATUS batteryStatus = new Kernel32.SYSTEM_POWER_STATUS();
		if (Kernel32.INSTANCE.GetSystemPowerStatus(batteryStatus) != 0) {
			raise_log(batteryStatus.toString());
			raise_batterychanged(batteryStatus.BatteryLifePercent, batteryStatus.ACLineStatus == 1);
			return true;
		}
		return false;
	
	}
	
	private void raise_log(String msg) {
		if (need_log_event) {
			if (msg!=null && msg.length()>0) {
				ba.raiseEventFromDifferentThread(msg, null, 0, event+"_log", false, new Object[] {msg});				
			}
		}
	}
	
	private void raise_batterychanged(int level, boolean plugged) {
		if (need_batterychanged_event) {
			ba.raiseEventFromDifferentThread(me, null, 0, event + "_batterychanged", true,
					new Object[] { level, plugged });
		}
	}
}

