/*
 * Copyright [yyyy] [name of copyright owner]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


// Anonymous function start
//
(function( window, undefined )
{

// reference
var Config			= window.h5glib.Config;
var Debug			= window.h5glib.Debug;
var Command			= window.h5glib.Command;
var Task			= window.h5glib.Task;
var SoundTask		= window.h5glib.SoundTask;
var ReadyTask		= window.h5glib.ReadyTask;
var ImageAnimator	= window.h5glib.ImageAnimator;
var Message			= window.h5glib.Message;
var MessageHandler	= window.h5glib.MessageHandler;
var MessageManager	= window.h5glib.MessageManager;
var SceneStatus		= window.h5glib.SceneStatus;
var Scene			= window.h5glib.Scene;

/**
 * Res
 */
var Res =
{
	String :
	{
		HTML_USAGE	: "<p>" +
					  "[←][→]: 回転 [↑]: ジャンプ [↓]: しゃがみ [Z]: 発声 [ESC]: メニューに戻る<br>" +
					  "</p>"
	},
	Color :
	{
		BACKGROUND		: "rgb(0, 0, 0)"
	},
	Font :
	{
		LARGE		: "bold 18px 'ＭＳ Ｐゴシック'",
		SMALL		: "bold 14px 'ＭＳ Ｐゴシック'"
	}
};

/**
 * MessageType
 */
var MessageType =
{
	NONE			: 0,
	RET_PREV_SCENE	: 1
};

/**
 * StageTask
 */
var StageTask = function( scene )
{
	this.command	= scene.command;	// input
};
StageTask.prototype = new Task();

(function( pt )
{
	/**
	 * 
	 */
	pt.update = function( scene )
	{
		var upd			= false;
		var msgManager	= scene.msgManager;

		// command
		if ( this.command.tbl.escape )
		{
			var message	= new Message( MessageType.RET_PREV_SCENE );
			msgManager.postBreakMessage( message );
		}
		return upd;
	};
	/**
	 * 
	 */
	pt.draw = function( scene )
	{
		var canvas		= scene.canvas;
		var context		= scene.context;

		context.save();

		context.fillStyle	= Res.Color.BACKGROUND;
		context.fillRect( 0, 0, canvas.width, canvas.height );

		context.restore();
	};
})( StageTask.prototype );

/**
 * ActorStatus
 */
var ActorStatus =
{
	NEUTRAL	: 0,
	JUMP	: 1,
	SQUAT	: 2,
	TURN_L	: 3,
	TURN_R	: 4
};

/**
 * ActorTask
 */
var ActorTask = function( scene )
{
	this.command		= scene.command;
	this.statusObjs		= null;
	this.animator		= null;
	this.trans			= null;
};
ActorTask.prototype = new Task();

(function( pt )
{
	/**
	 * 
	 */
	pt.init = function( scene )
	{
		var image		= scene.data.resource.image;
		var animation	= scene.data.animation;
		this.statusObjs	=
		[
			{ update : this.updateNeutral,	animator : new ImageAnimator( image.actorNeutral.data,	animation.actorNeutral ) },
			{ update : this.updateAction,	animator : new ImageAnimator( image.actorJump.data,		animation.actorAction ) },
			{ update : this.updateAction,	animator : new ImageAnimator( image.actorSquat.data,	animation.actorAction ) },
			{ update : this.updateAction,	animator : new ImageAnimator( image.actorTurnL.data,	animation.actorAction ) },
			{ update : this.updateAction,	animator : new ImageAnimator( image.actorTurnR.data,	animation.actorAction ) }
		];
		this.setStatus( ActorStatus.NEUTRAL );
	};
	/**
	 * 
	 */
	pt.setStatus = function( status )
	{
		this.status	= status;

		var sobj		= this.statusObjs[ this.status ];
		this.update		= sobj.update;
		this.animator	= sobj.animator;
	};
	/**
	 * 
	 */
	pt.updateNeutral = function( scene )
	{
		var upd = false;
		var sound	= scene.soundTask;

		if ( this.command.tbl.up )
		{
			this.setStatus( ActorStatus.JUMP );
			this.animator.start();
		}
		else if ( this.command.tbl.down )
		{
			this.setStatus( ActorStatus.SQUAT );
			this.animator.start();
		}
		else if ( this.command.tbl.right )
		{
			this.setStatus( ActorStatus.TURN_L );
			this.animator.start();
		}
		else if ( this.command.tbl.left )
		{
			this.setStatus( ActorStatus.TURN_R );
			this.animator.start();
		}
		else if ( this.command.tbl.voice )
		{
			sound.prepare("voice");
		}

		if ( this.status != ActorStatus.NEUTRAL )
		{
			return true;
		}

		// neutral animation
		if ( this.animator.isActive() )
		{
			upd = this.animator.proceed();
		}
		else
		{
			var r = Math.floor( Math.random() * 20 );
			if ( r == 1 )
			{
				this.animator.start();
				upd = true;
			}
		}
		return upd;
	};
	/**
	 * 
	 */
	pt.updateAction = function( scene )
	{
		var upd = false;

		if ( this.animator.isActive() )
		{
			upd = this.animator.proceed();
		}
		else
		{
			this.setStatus( ActorStatus.NEUTRAL );
			upd = true;
		}
		return upd;
	};

	/**
	 * 
	 */
	pt.draw = function( scene )
	{
		var canvas		= scene.canvas;
		var context		= scene.context;
		var resource	= scene.data.resource;

		if ( this.trans == null )
		{
			this.trans		= { x : ( canvas.width / 2 ), y : ( canvas.height / 2 ) };
		}
		context.drawImage(
			this.animator.image,
			this.animator.fx,							// sx
			this.animator.fy,							// sy
			this.animator.fw,							// sw
			this.animator.fh,							// sh
			this.trans.x - ( this.animator.fw / 2 ),	// dx
			this.trans.y - ( this.animator.fh / 2 ),	// dy
			this.animator.fw,							// dw
			this.animator.fh							// dh
		);
	};
})( ActorTask.prototype );

/**
 * DebugTask
 */
var DebugTask = function( scene )
{
	this.command	= scene.command;	// input
	this.info		= null;
	this.lag		= 0;
};
DebugTask.prototype = new Task();

(function( pt )
{
	pt.LAG_VAL	= 10;

	/**
	 * 
	 */
	pt.update = function( scene )
	{
		var upd = false;
		// lag
		if ( this.lag )
		{
			this.lag--;
		}
		else
		{
			if ( this.command.tbl.debug )
			{
				this.info	= "scene.actorTask.anim=" + scene.actorTask.anim;
				this.lag	= this.LAG_VAL;
				upd = true;
			}
		}
		return upd;
	};

	/**
	 * 
	 */
	pt.draw = function( scene )
	{
		// output debug info
		if ( this.info )
		{
			Debug.print( this.info );
			this.info = null;
		}
	};
})( DebugTask.prototype );

/**
 * InputCommand
 */
var InputCommand = function()
{
	this.tbl.up		= 0;
	this.tbl.down	= 0;
	this.tbl.left	= 0;
	this.tbl.right	= 0;
	this.tbl.voice	= 0;
	this.tbl.escape	= 0;
	this.tbl.debug	= 0;
};
InputCommand.prototype = new Command();

(function( pt )
{
	/**
	 * 
	 */
	pt.update = function() {};
	/**
	 * 
	 */
	pt.handleSysEvent = function( event )
	{
		var type = event.type.toLowerCase();
		if ( type.substring( 0, 3 ) == "key" )
		{
			var value = 0;
			if      ( type == "keydown" ) { value = 1; }
			else if ( type == "keyup"   ) { value = 0; }

			switch ( event.keyCode )
			{
				case 37: this.tbl.left	= value; break;	// ←
				case 39: this.tbl.right	= value; break;	// →
				case 38: this.tbl.up	= value; break;	// ↑
				case 40: this.tbl.down	= value; break;	// ↓
				case 90: this.tbl.voice	= value; break;	// Z
				case 27: this.tbl.escape= value; break;	// ESC
				case 81: this.tbl.debug	= value; break;	// Q
			}
		}
	};
})( InputCommand.prototype );

/**
 * RorinScene
 */
var RorinScene = function( app, name )
{
	this.app			= app;
	this.name			= name;
	this.data			= null;
	this.command		= new InputCommand();

	// create task
	this.readyTask		= new ReadyTask( this );
	this.stageTask		= new StageTask( this );
	this.actorTask		= new ActorTask( this );
	this.soundTask		= new SoundTask( this );
	this.debugTask		= new DebugTask( this );
	// create list
	this.stageTask.append( this.actorTask );
	this.stageTask.append( this.soundTask );
	this.stageTask.append( this.debugTask );

	this.headTasks		=
	[
		this.readyTask,
		this.stageTask,
		this.readyTask
	];
	this.setStatus( SceneStatus.READY );

	// message handler
	this.msgManager		= new MessageManager();
	this.msgManager.addHandler( new MessageHandler( MessageType.RET_PREV_SCENE,	this, this.handleRetPrevScene ) );
};
RorinScene.prototype = new Scene();

(function( pt )
{
	/**
	 * 
	 */
	pt.handleRetPrevScene = function( scene, message )
	{
		this.app.sceneManager.pop();
		var prevScene = this.app.sceneManager.current;
		prevScene.show();
	};
	/**
	 * 
	 */
	pt.setStatus = function( status )
	{
		this.status	= status;
		this.child	= this.headTasks[ this.status ];
	};

	/**
	 * 
	 */
	pt.init = function()
	{
		// window.onload のタイミング
	};
	/**
	 * 
	 */
	pt.show = function()
	{
		this.setUsage( Res.String.HTML_USAGE );

		this.command.clear();
		this.holdCanvas();
		this.drawChildren( this );
	};

	/**
	 * 
	 */
	pt.setData = function( data )
	{
		this.data		= data;
		// init actor
		this.actorTask.init( this );
	};
	/**
	 * 
	 */
	pt.getData = function()
	{
		return this.data;
	};
	/**
	 * 
	 */
	pt.loadData = function( data )
	{
		try
		{
			// load resource
			this.app.loadResource( this.name, data.resource );
			// set data
			this.setData( data );
			// set status
			var self = this;
			window.setTimeout( function() { self.setStatus( SceneStatus.RUNNING ); self.show(); }, Config.loadInterval );
		}
		catch ( e )
		{
			this.app.kill();
			Debug.alertError( e );
		}
	};
})( RorinScene.prototype );


// Expose
if ( !window.h5glib ) { window.h5glib = {}; }
window.h5glib.RorinScene	= RorinScene;

// Anonymous function end
//
})( window );
