package com.example.PhidgetPowerGuardExample;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.phidget22.*;

public class PowerGuardExample extends Activity {

	PowerGuard ch;
	SeekBar overVoltageBar;
	CheckBox powerEnabledBox;
	
	Toast errToast;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Hide device information and settings until one is attached
		LinearLayout settingsAndData = (LinearLayout) findViewById(R.id.settingsAndData);
		settingsAndData.setVisibility(LinearLayout.GONE);

		//set data interval seek bar functionality
		overVoltageBar = (SeekBar) findViewById(R.id.overVoltageBar);
		overVoltageBar.setOnSeekBarChangeListener(new overVoltageChangeListener());

		//set up power enabled functionality
		powerEnabledBox = (CheckBox) findViewById(R.id.powerEnabledBox);
		powerEnabledBox.setOnCheckedChangeListener(new powerEnabledChangeListener());

        try
        {
        	ch = new PowerGuard();

        	//Allow direct USB connection of Phidgets
			if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_HOST))
                com.phidget22.usb.Manager.Initialize(this);

			//Enable server discovery to list remote Phidgets
			this.getSystemService(Context.NSD_SERVICE);
			Net.enableServerDiscovery(ServerType.DEVICE_REMOTE);

			ch.addAttachListener(new AttachListener() {
				public void onAttach(final AttachEvent attachEvent) {
				    AttachEventHandler handler = new AttachEventHandler(ch);
                    synchronized(handler)
					{
						runOnUiThread(handler);
						try {
							handler.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});

			ch.addDetachListener(new DetachListener() {
				public void onDetach(final DetachEvent detachEvent) {
                    DetachEventHandler handler = new DetachEventHandler(ch);
                    synchronized(handler)
					{
						runOnUiThread(handler);
						try {
							handler.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});

			ch.addErrorListener(new ErrorListener() {
				public void onError(final ErrorEvent errorEvent) {
					ErrorEventHandler handler = new ErrorEventHandler(ch, errorEvent);
					runOnUiThread(handler);
				}
			});

			ch.open();
        } catch (PhidgetException pe) {
	        pe.printStackTrace();
		}

    }

	private class overVoltageChangeListener implements SeekBar.OnSeekBarChangeListener {
		public void onProgressChanged(SeekBar seekBar, int progress,
									  boolean fromUser) {
			try {
				TextView overVoltageTxt = (TextView) findViewById(R.id.overVoltageTxt);
				double overVoltage = ((double)progress/seekBar.getMax()) *
						(ch.getMaxOverVoltage() - ch.getMinOverVoltage()) + ch.getMinOverVoltage();

				//round overvoltage to 2 decimal places
				overVoltage = Math.round(overVoltage * 100) / 100.0;

				overVoltageTxt.setText(String.valueOf(overVoltage) + " V");
				ch.setOverVoltage(overVoltage);
			} catch (PhidgetException e) {
				e.printStackTrace();
			}
		}

		public void onStartTrackingTouch(SeekBar seekBar) {}

		public void onStopTrackingTouch(SeekBar seekBar) {}
	}

	private class powerEnabledChangeListener implements CheckBox.OnCheckedChangeListener {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
		{
			try {
				ch.setPowerEnabled(isChecked);
			} catch (PhidgetException e) {
				e.printStackTrace();
			}
		}
	}

    class AttachEventHandler implements Runnable { 
    	Phidget ch;

		public AttachEventHandler(Phidget ch) {
			this.ch = ch;
		}

		public void run() {
			LinearLayout settingsAndData = (LinearLayout) findViewById(R.id.settingsAndData);
			settingsAndData.setVisibility(LinearLayout.VISIBLE);

			TextView attachedTxt = (TextView) findViewById(R.id.attachedTxt);

			attachedTxt.setText("Attached");
			try {
				TextView nameTxt = (TextView) findViewById(R.id.nameTxt);
				TextView serialTxt = (TextView) findViewById(R.id.serialTxt);
				TextView versionTxt = (TextView) findViewById(R.id.versionTxt);
				TextView channelTxt = (TextView) findViewById(R.id.channelTxt);
				TextView hubPortTxt = (TextView) findViewById(R.id.hubPortTxt);
				TextView labelTxt = (TextView) findViewById(R.id.labelTxt);

				nameTxt.setText(ch.getDeviceName());
				serialTxt.setText(Integer.toString(ch.getDeviceSerialNumber()));
				versionTxt.setText(Integer.toString(ch.getDeviceVersion()));
				channelTxt.setText(Integer.toString(ch.getChannel()));
				hubPortTxt.setText(Integer.toString(ch.getHubPort()));
				labelTxt.setText(ch.getDeviceLabel());

				double maxOverVoltage = ((PowerGuard)ch).getMaxOverVoltage();
				double minOverVoltage = ((PowerGuard)ch).getMinOverVoltage();
				double overVoltage = minOverVoltage;

				((PowerGuard)ch).setOverVoltage(overVoltage);

				TextView overVoltageTxt = (TextView) findViewById(R.id.overVoltageTxt);
				overVoltageTxt.setText(String.valueOf(overVoltage) + " V");

				SeekBar overVoltageBar = (SeekBar) findViewById(R.id.overVoltageBar);
				overVoltageBar.setProgress((int)((overVoltage - minOverVoltage)/(maxOverVoltage - minOverVoltage) * overVoltageBar.getMax()));

				powerEnabledBox.setChecked(((PowerGuard)ch).getPowerEnabled());

			} catch (PhidgetException e) {
				e.printStackTrace();
			}

			// Notify that we're done
			synchronized(this) {
				this.notify();
			}

		}
    }
    
    class DetachEventHandler implements Runnable {
    	Phidget ch;
    	
    	public DetachEventHandler(Phidget ch) {
    		this.ch = ch;
    	}
    	
		public void run() {
			LinearLayout settingsAndData = (LinearLayout) findViewById(R.id.settingsAndData);

			settingsAndData.setVisibility(LinearLayout.GONE);

			TextView attachedTxt = (TextView) findViewById(R.id.attachedTxt);
			attachedTxt.setText("Detached");

			TextView nameTxt = (TextView) findViewById(R.id.nameTxt);
			TextView serialTxt = (TextView) findViewById(R.id.serialTxt);
			TextView versionTxt = (TextView) findViewById(R.id.versionTxt);
			TextView channelTxt = (TextView) findViewById(R.id.channelTxt);
			TextView hubPortTxt = (TextView) findViewById(R.id.hubPortTxt);
			TextView labelTxt = (TextView) findViewById(R.id.labelTxt);

			nameTxt.setText(R.string.unknown_val);
			serialTxt.setText(R.string.unknown_val);
			versionTxt.setText(R.string.unknown_val);
			channelTxt.setText(R.string.unknown_val);
			hubPortTxt.setText(R.string.unknown_val);
			labelTxt.setText(R.string.unknown_val);

			// Notify that we're done
			synchronized(this) {
				this.notify();
			}
		}
    }

	class ErrorEventHandler implements Runnable {
		Phidget ch;
		ErrorEvent errorEvent;

		public ErrorEventHandler(Phidget ch, ErrorEvent errorEvent) {
			this.ch = ch;
			this.errorEvent = errorEvent;
		}

		public void run() {
			 if (errToast == null)
				 errToast = Toast.makeText(getApplicationContext(), errorEvent.getDescription(), Toast.LENGTH_SHORT);

			 //replace the previous toast message if a new error occurs
			 errToast.setText(errorEvent.getDescription());
			 errToast.show();
        }
	}

    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	try {
			ch.close();

		} catch (PhidgetException e) {
			e.printStackTrace();
		}

		//Disable USB connection to Phidgets
    	if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_HOST))
            com.phidget22.usb.Manager.Uninitialize();
    }

}

