/**
 * This is a test application for the distriqt extension
 * 
 * @author Michael Archbold & Shane Korin
 * 	
 */
package
{
	import com.distriqt.extension.nativewebview.NativeWebView;
	import com.distriqt.extension.nativewebview.WebView;
	import com.distriqt.extension.nativewebview.WebViewOptions;
	import com.distriqt.extension.nativewebview.events.NativeWebViewEvent;
	import com.distriqt.utils.FileUtils;
	
	import flash.desktop.NativeApplication;
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TouchEvent;
	import flash.filesystem.File;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.ui.Keyboard;
	
	
	[SWF(backgroundColor="#cccccc")]
	/**	
	 * Sample application for using the NativeWebView Native Extension
	 */
	public class TestNativeWebView extends Sprite
	{
		
		/**
		 * Class constructor 
		 */	
		public function TestNativeWebView()
		{
			super();
			create();
			init();
		}
		
		
		//
		//	VARIABLES
		//
		
		private var _text		: TextField;
		private var _bitmap		: Bitmap;
		
		
		//
		//	INITIALISATION
		//	

		private function create( ):void
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			_bitmap = new Bitmap();
			addChild( _bitmap );
			
			_text = new TextField();
			_text.y = 40;
			_text.defaultTextFormat = new TextFormat( "_typewriter", 16 );
			addChild( _text );

			stage.addEventListener( Event.RESIZE, stage_resizeHandler, false, 0, true );
			stage.addEventListener( MouseEvent.CLICK, mouseClickHandler, false, 0, true );
		
			NativeApplication.nativeApplication.addEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler, false, int.MAX_VALUE );
		}
		
		
		private function init( ):void
		{
			try
			{
				message( "NativeWebView Supported: " + NativeWebView.isSupported );
				message( "NativeWebView Version:   " + NativeWebView.service.version );
				
				// Copy www directory to accessible location (required for Android but works for iOS as well)
				var destination:File = File.applicationStorageDirectory.resolvePath( "www" );
				if (!destination.exists)
				{
					var packagedWWWRoot:File = File.applicationDirectory.resolvePath( "www" );
					FileUtils.copyTo( packagedWWWRoot, destination );
				}
				
			}
			catch (e:Error)
			{
				message( "ERROR::"+e.message );
			}
		}
		
		
		//
		//	FUNCTIONALITY
		//
		
		private function message( str:String ):void
		{
			trace( str );
			_text.text = str+"\n" + _text.text;
		}
		
		
		private function createWebView( viewPort:Rectangle=null ):WebView
		{
			message( "Creating web view" );
			
			
			
			var webView:WebView;
				
			if (viewPort == null)
			{
				viewPort = new Rectangle( 0, Math.floor(stage.stageHeight * 0.5), stage.stageWidth, Math.floor(stage.stageHeight * 0.5) );
			}
				
			var options:WebViewOptions = new WebViewOptions();
			options.allowInlineMediaPlayback = true;
			options.bounces = false;
			options.mediaPlaybackRequiresUserAction = false;
			options.backgroundColour = 0xffffff;
			options.keyboardDisplayRequiresUserAction = false;

			webView = NativeWebView.service.createWebView( viewPort, options, stage );
			message( "start location: "+webView.location );
			
			webView.addEventListener( NativeWebViewEvent.LOCATION_CHANGING, webView_locationChangingHandler );
			webView.addEventListener( NativeWebViewEvent.LOCATION_CHANGE, webView_locationChangeHandler );
			webView.addEventListener( NativeWebViewEvent.COMPLETE, webView_completeHandler );
			webView.addEventListener( NativeWebViewEvent.ERROR, webView_errorHandler );
			webView.addEventListener( NativeWebViewEvent.JAVASCRIPT_RESPONSE, webView_javascriptResponseHandler );
			webView.addEventListener( NativeWebViewEvent.JAVASCRIPT_MESSAGE, webView_javascriptMessageHandler );
			webView.addEventListener( NativeWebViewEvent.FOCUS_IN, webView_focusHandler );
			webView.addEventListener( NativeWebViewEvent.FOCUS_OUT, webView_focusHandler );
			webView.addEventListener( TouchEvent.TOUCH_TAP, webView_tapHandler );
		
			
			return webView;
		}
		
		
		private function removeWebView( webView:WebView ):void
		{
			if (webView != null)
			{
				webView.removeEventListener( NativeWebViewEvent.LOCATION_CHANGING, webView_locationChangingHandler );
				webView.removeEventListener( NativeWebViewEvent.LOCATION_CHANGE, webView_locationChangeHandler );
				webView.removeEventListener( NativeWebViewEvent.COMPLETE, webView_completeHandler );
				webView.removeEventListener( NativeWebViewEvent.ERROR, webView_errorHandler );
				webView.removeEventListener( NativeWebViewEvent.JAVASCRIPT_RESPONSE, webView_javascriptResponseHandler );
				webView.removeEventListener( NativeWebViewEvent.JAVASCRIPT_MESSAGE, webView_javascriptMessageHandler );
				webView.removeEventListener( NativeWebViewEvent.FOCUS_IN, webView_focusHandler );
				webView.removeEventListener( NativeWebViewEvent.FOCUS_OUT, webView_focusHandler );
				webView.removeEventListener( TouchEvent.TOUCH_TAP, webView_tapHandler );
				webView.dispose();
				webView = null;
			}
		}
		
		
		////////////////////////////////////////////////////////
		//	EXAMPLES
		//
		
		private var webViews:Array = [];
		
		
		private function loadSomeContent( webView:WebView ):void
		{
//			if (Math.random() > 0.5)
//			{
				loadPackagedFile( webView );	
//			}
//			else
//			{
//				loadFromUrl( webView );
//			}
		}


		private function loadFromUrl( webView:WebView ):void
		{
			//
			//	Load urls
			message( "Load url" );
			
			webView.loadURL( "http://www.google.com" );
			
//			webView.loadURL( "data:image/png;base64,[encoded data, 5616 characters]" );
//			webView.loadURL( "http://html5demos.com/video" );
//			webView.loadURL( "http://www.quirksmode.org/html5/tests/video.html" );
//			webView.loadURL( "http://labsdownload.adobe.com/pub/labs/flashruntimes/shared/air18_flashplayer18_releasenotes.pdf" );
//			webView.loadURL( "http://dev.schimpanz.com/androidtest/input.html" );
			
		}
		
		
		private function loadPackagedFile( webView:WebView ):void
		{
			//
			//	Load an application packaged file, in a 'www' directory
			message( "Load packaged file" );
			
			//	Grab the file url
			var filename:String = "www/textinput.html";
//			if (Math.random() > 0.5) filename = "www/video.html"
				
			var file:File = File.applicationStorageDirectory.resolvePath( filename );
			
			message( file.nativePath +"["+file.exists+"]");
			
			webView.loadURL( "file://" + file.nativePath + "?test=get" );
			
		}
		
		
		
		//
		//	EVENT HANDLERS
		//
		
		private function stage_resizeHandler( event:Event ):void
		{
			_text.width  = stage.stageWidth;
			_text.height = stage.stageHeight - 100;
		}
		

		private var _viewPort:Rectangle;
		
		private function mouseClickHandler( event:MouseEvent ):void
		{
			//
			//	Do something when user clicks screen
			//	
			if (NativeWebView.isSupported)
			{
				var webView:WebView;
				
//				if (webViews.length >= 2)
//				{
//					for (var i:int = 0; i < webViews.length; i++)
//					{
//						removeWebView( webViews[i] );
//					}
//					webViews = [];
//					_viewPort = null;
//				}
//				else
				if (webViews.length < 2)
				{
					var height:int = Math.floor(stage.stageHeight * 0.5 / 2);
					if (_viewPort == null) _viewPort = new Rectangle( 0, Math.floor(stage.stageHeight * 0.5), stage.stageWidth, height );
					else _viewPort.y += height;
					
					webView = createWebView( _viewPort );
					
					webViews.push( webView );
					
					loadSomeContent( webView );
				}
			}
		}
		
		
		//
		//	EXTENSION HANDLERS
		//
		
		
		private function webView_locationChangingHandler( event:NativeWebViewEvent ):void
		{
			message( "location changing: " + event.data );
			
			// Cancel this operation by calling `event.preventDefault()'
//			event.preventDefault();
		}

		private function webView_locationChangeHandler( event:NativeWebViewEvent ):void
		{
			message( "location change: " + event.data );
		}
		
		private function webView_completeHandler( event:NativeWebViewEvent ):void
		{
			message( "COMPLETE:: " + event.data );
			
			message( "Title:      " + WebView(event.currentTarget).title );
			message( "Location:   " + WebView(event.currentTarget).location );
			message( "UserAgent:  " + WebView(event.currentTarget).userAgent );
			message( "StatusCode: " + WebView(event.currentTarget).statusCode );
		}
		
		private function webView_errorHandler( event:NativeWebViewEvent ):void
		{
			message( "ERROR:: " + event.data );
		}
		
		private function webView_javascriptResponseHandler( event:NativeWebViewEvent ):void
		{
			message( "Javascript Response: " + event.data );
		}
		
		private function webView_javascriptMessageHandler( event:NativeWebViewEvent ):void
		{
			message( "Javascript Message: " + event.data );
		}
		
		private function webView_tapHandler( event:TouchEvent ):void
		{
			message( "Tap: "+ event.localX+"x"+event.localY );
		}
		
		private function keyDownHandler( event:KeyboardEvent ):void
		{
			message( "keyDownHandler(): " + event.keyCode );
			switch (event.keyCode)
			{
				case Keyboard.BACK:
					event.preventDefault();
					event.stopImmediatePropagation();
					break;
			}
		}
		
		private function webView_focusHandler( event:NativeWebViewEvent ):void
		{
			message( event.type );
		}
		
		
	}
}

