using UnityEngine;
using System;
using System.Collections;
using MiMic.CsApi;
using MiMic.CsApi.LPC1769;

public class LPCXpresso1769_LedSwitch : MonoBehaviour
{
	//Pin option for digital out
	static GpioPin.Option DIGITAL_OUT=new GpioPin.Option(1,new Pin.Option(null,1,0));
	//Pin option for digital in
	static GpioPin.Option DIGITAL_IN=new GpioPin.Option(0,new Pin.Option(null,0,0));

	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update (){
	
	}
	
	private Mcu _mcu;
	private GpioPin gpiopin;
	/**
	 * The MiMic Event callback
	 * (This callback function is called by MiMic.MCU instance in periodic)
	 */
	public void _mcuCallback()
	{
		//call the periodic proc here.
		this._mcu.periodicProc();
	}
	/**
	 * Application state
	 */
	private enum ST
	{
		INIT,//initialize
		WAIT,//wait for connection
		ERROR,//error will be return initialize
		RUN
	};
	private ST _app_st=ST.INIT;
	public void onActivateChangedHandler(bool i_param)
	{
		if(!i_param){
			this._app_st=ST.ERROR;
		}
	}
	void OnGUI()
	{
		switch(this._app_st)
		{
		case ST.INIT:
			//initialize section
			GUI.BeginGroup (new Rect (Screen.width / 2 - 100, Screen.height / 2 - 100, 200, 100));
			GUI.Box(new Rect (0,0,200,100), "Input your MiMic IP Address");
			string ts=GUI.TextField (new Rect (20,40,160,20), this._mcu_ip_addr,19);
			if(ts!=this._mcu_ip_addr){
				this._mcu_ip_addr=ts;
			}
			if(GUI.Button (new Rect (100-40,65,80,30), "Connect")){
				//change state
				this._app_st=ST.WAIT;
			}
			GUI.EndGroup ();
			break;
		case ST.WAIT:
			try{
				GUI.Box(new Rect (Screen.width / 2 - 100, Screen.height / 2 - 100,200,50), "Connect to "+this._mcu_ip_addr+" ...");
				//The constructor throw an exception when failed.
				this._mcu=new Mcu(this,"_mcuCallback",this._mcu_ip_addr,false);
				this._mcu.onActivateChanged=this.onActivateChangedHandler;
				this._mcu.activate();
				this.gpiopin=(GpioPin)this._mcu.getPin(LPCXpresso1769.LED[0],"GPIO");
				this.gpiopin.setOpt(DIGITAL_OUT);
				this._app_st=ST.RUN;
			}catch(Exception e){
				this._app_st=ST.ERROR;
			}
			break;
		case ST.RUN:
			if(GUI.Button(new Rect (0,0,200,50),"P0[22] - ON")){
				this.gpiopin.setValue(1);
			}
			if(GUI.Button(new Rect (0,52,200,50),"P0[22] - OFF")){
				this.gpiopin.setValue(0);
			}
			break;
		case ST.ERROR:
			GUI.BeginGroup (new Rect (Screen.width / 2 - 100, Screen.height / 2 - 100, 200, 100));
			GUI.Box(new Rect (0,0,200,100), "Can not connect to "+this._mcu_ip_addr);
			if(GUI.Button (new Rect (100-40,65,80,30), "Return")){
				this._app_st=ST.INIT;
				this.gpiopin=null;
			}
			GUI.EndGroup();
			break;
				
		}
		
	}
	//
	// Properties
	//
	private string _mcu_ip_addr="192.168.128.39";
	
}
