/**
 * 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.NativeWebViewOptions;
	import com.distriqt.extension.nativewebview.PrintOptions;
	import com.distriqt.extension.nativewebview.WebView;
	import com.distriqt.extension.nativewebview.WebViewOptions;
	import com.distriqt.extension.nativewebview.events.NativeWebViewEvent;
	import com.distriqt.test.nativewebview.FileUtils;

	import flash.desktop.NativeApplication;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	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;

	/**
	 * 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;
		private var _webView:WebView = null;


		//
		//	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 = Math.floor( stage.stageHeight * 0.5 );
			_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 );

				if (NativeWebView.isSupported)
				{
					NativeWebView.service.initialisePlatform(
							new NativeWebViewOptions(),
							function (success:Boolean)
							{
							}
					);
				}
			}
			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():void
		{
			if (_webView == null)
			{
				message( "Creating web view" );

				var viewPort:Rectangle = new Rectangle( 0, Math.floor( stage.stageHeight * 0.5 ), stage.stageWidth, Math.floor( stage.stageHeight * 0.5 ) );

//				graphics.beginFill( 0xFF0000 );
//				graphics.drawRect( viewPort.x, viewPort.y, viewPort.width, viewPort.height );
//				graphics.endFill();

				var options:WebViewOptions = new WebViewOptions();
				options.allowInlineMediaPlayback = true;
				options.bounces = false;
				options.mediaPlaybackRequiresUserAction = false;
				options.allowZooming = false;
				options.allowScrolling = false;

				options.backgroundColour = 0xCED2D0;
				options.backgroundEnabled = true;

//				options.disableLongPressGestures = true;
//				options.cachePolicy = CachePolicy.LOAD_DEFAULT;
				options.useWebKitIfAvailable = true;


				_webView = NativeWebView.service.createWebView( viewPort, options );

				_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( TouchEvent.TOUCH_TAP, webView_tapHandler );

			}

		}


		private function removeWebView():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( TouchEvent.TOUCH_TAP, webView_tapHandler );
				_webView.dispose();
				_webView = null;
			}
		}


		////////////////////////////////////////////////////////
		//	EXAMPLES
		//


		private function loadFromAString():void
		{
			//
			//	Load from a string
			message( "Load from a string" );

//			var html:String =
//<![CDATA[<video id="video1" width="100%" height="100%" controls autoplay webkit-playsinline>
//	<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
//	<source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
//	Your browser does not support HTML5 video.
//</video>]]>;
//			
//			_webView.loadString( html );

			if (NativeWebView.service.version.indexOf( "Android" ) > 0)
			{
				// Android: Copy the application packaged files to an accessible location			
				var packagedWWWRoot:File = File.applicationDirectory.resolvePath( "www" );
				var destination:File = File.applicationStorageDirectory.resolvePath( "www" );
				packagedWWWRoot.copyTo( destination, true );
			}

			var html:String =
						'<video id="video1" width="100%" height="100%" controls autoplay webkit-playsinline> \
							<source src="www/videos/big_buck_bunny.mp4" type="video/mp4"> \
							Your browser does not support HTML5 video. \
						</video>';

			_webView.loadString( html, "text/html", "file://" + File.applicationStorageDirectory.nativePath + "/" );
		}

		private function loadFromUrl():void
		{
			//
			//	Load urls
			message( "Load url" );

//			_webView.loadURL( "data:image/png;base64,[encoded data, 5616 characters]" );
			_webView.loadURL( "https://maps.google.com/" );
//			_webView.loadURL( "https://html5demos.com/video" );
//			_webView.loadURL( "https://www.quirksmode.org/html5/tests/video.html" );
//			_webView.loadURL( "https://labsdownload.adobe.com/pub/labs/flashruntimes/shared/air18_flashplayer18_releasenotes.pdf" );

//			_webView.loadURL( "https://airnativeextensions.com" );

//			_webView.loadURL( "https://google-developers.appspot.com/maps/documentation/javascript/examples/full/map-simple" );

//			_webView.loadURL( "https://www.youtube.com/watch?v=7bDLIV96LD4" );

		}

		private function loadPackagedFile():void
		{
			//
			//	Load an application packaged file, in a 'www' directory
			message( "Load packaged file" );
			var filePath:String = "textinput.html";
			var file:File = getPackagedFilesDirectory().resolvePath( filePath );
			var fileUrl:String = "file://" + file.nativePath;

			message( fileUrl );
			_webView.loadURL( fileUrl );
		}


		private function drawBitmap():void
		{
			//
			//	Draw to bitmap
			message( "Draw to bitmap" );

			var bd:BitmapData = new BitmapData( _webView.width, _webView.height );
			_webView.drawViewPortToBitmapData( bd );
			_bitmap.bitmapData = bd;
		}

		private function javascript():void
		{
			//
			//	Javascript examples
			message( "Javascript example" );

//			_webView.evaluateJavascript( "document.body.style.backgroundColor='#f00';" );
//			_webView.evaluateJavascript( "alert( 'test' )" );
//			_webView.evaluateJavascript( "document.documentElement.outerHTML" );
//			_webView.evaluateJavascript( "(function() { document.getElementsByTagName('video')[0].play(); })()" );

			_webView.evaluateJavascript( "window.location.href" );

			// Alternative method (will not trigger response event)
//			_webView.loadURL( "javascript:alert('test')" );
		}

		private function print():void
		{
			//
			// 	Print example
			message( "Print example" );

			if (_webView.isPrintSupported)
			{
				message( "Printing" );
				var po:PrintOptions = new PrintOptions();
				_webView.print( po );
			}
		}

		private function resize():void
		{
			//
			//	Resize example
			message( "Resize example" );

			_webView.width += 10;
			_webView.height += 10;
			_webView.x += 3;
			_webView.y -= 3;
		}


		//
		//	EVENT HANDLERS
		//

		private function stage_resizeHandler( event:Event ):void
		{
//			_text.y = Math.floor( stage.stageHeight * 0.5 );
			_text.width = stage.stageWidth;
			_text.height = Math.floor( stage.stageHeight * 0.5 ) - 100;
		}


		private function mouseClickHandler( event:MouseEvent ):void
		{
			//
			//	Do something when user clicks screen
			//	
			if (NativeWebView.isSupported)
			{
				if (_webView == null)
				{
					createWebView();

					//
					//	Perform a load

//					loadFromUrl();
					loadPackagedFile();
//					loadFromAString();

				}
				else
				{
					//
					//	Perform an example

//					drawBitmap();
//					javascript();
//					print();
					resize();

//					if (_webView.canGoBack)
//					{
//						_webView.historyBack();
//					}

//					removeWebView();
				}


			}
		}


		//
		//	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( "Location:   " + _webView.location );
			message( "UserAgent:  " + _webView.userAgent );
			message( "StatusCode: " + _webView.statusCode );
//			message( "HTML: " + _webView.htmlSource );
		}

		private function webView_errorHandler( event:NativeWebViewEvent ):void
		{
			message( "ERROR:: " + event.data );
			message( "Location:   " + _webView.location );
		}

		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 getPackagedFilesDirectory():File
		{
			var directory:File = File.applicationDirectory.resolvePath( "www" );
			if (NativeWebView.service.implementation == "Android")
			{
				// Android: Copy the application packaged files to an accessible location
				directory = File.applicationStorageDirectory.resolvePath( "www" );
				if (!directory.exists)
				{
					var packagedWWWRoot:File = File.applicationDirectory.resolvePath( "www" );
					FileUtils.copyTo( packagedWWWRoot, directory );
				}
			}
			// Do nothing for iOS, can access applicationDirectory directly
			return directory;
		}

	}
}

