/*
Copyright (c) Ubiquitous Entertainment Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
class Timeline {
	entity:E;
	queue:Action[];
	paused:bool;
	looped:bool;
	_activated:bool;
	_parallel:ParallelAction;
	isFrameBased:bool;

	/**
	 * アニメーションを管理するためのクラス.
	 *
	 * 操作するエンティティひとつに対して、必ずひとつのタイムラインが対応する。
	 * Timelineクラス を読み込むと、Entity クラスを継承したすべてのクラスの
	 * tl プロパティに、タイムラインクラスのインスタンスが生成される。
	 * 
	 * タイムラインクラスは、自身に様々なアクションを追加するメソッドを持っており、
	 * これらを使うことで簡潔にアニメーションや様々な操作をすることができる。
	 * タイムラインクラスはフレームとタイムのアニメーションができる。
	 * 
	 * 元ソースはenchant.jsに提供されていたtl.enchant.jsです。
	 * http://enchantjs.com/ja/
	 *
	 * @param entity 操作の対象となるEntity
	*
	 */
	constructor(entity:E) {
		this.entity = entity;
		this.queue = new Action[];
		this.paused = false;
		this.looped = false;
		this._parallel = null;
		this._activated = false;
	}

	_deactivateTimeline(force?:bool) {
		if (force || this._activated) {
			this._activated = false;
			if (this.entity.scene)
				this.entity.scene.game.update.remove(this, this.tick);
			else
				this.entity.addActiveQueue(() => {
					this.entity.scene.game.update.remove(this, this.tick);
				});
		}
	}

	_activateTimeline(force?:bool) {
		if (force || (!this._activated && !this.paused)) {
			if (this.entity.scene)
				this.entity.scene.game.update.handle(this, this.tick);
			else
				this.entity.addActiveQueue(() => {
					this.entity.scene.game.update.handle(this, this.tick);
				});
			this._activated = true;
		}
	}

	setFrameBased() {
		this.isFrameBased = true;
	}

	setTimeBased() {
		this.isFrameBased = false;
	}

	next(remainingTime?:number) {
		var action = this.queue.shift();
		if (! action)	//おそらくdestoryされてしまっている
			return;
		if (action.action_end) {
			action.action_end.fire({timeline: this});
		}

		if (this.queue.length === 0 && !this.looped) {
			this._deactivateTimeline(true);
			return;
		}

		if (this.looped) {
			action.removed_from_timeline.fire({timeline: this});
			action.frame = 0;

			this.add(action);
		} else {
			// remove after dispatching removedfromtimeline event
			action.removed_from_timeline.fire({timeline: this});
		}
		if (remainingTime > 0 || (this.queue[0] && this.queue[0].time === 0)) {
			this.tick(remainingTime);
		}
	}

	tick(t:number) {
		if (this.paused) {
			return;
		}
		if (this.queue.length > 0) {
			var action = this.queue[0];
			if (action.frame === 0) {
				if (action.action_start) {
					action.action_start.fire({timeline: this});
				}
			}

			action.action_tick.fire({
				timeline: this,
				elapsed: (this.isFrameBased) ? 1 : t
			})
		}
	}

	add(action:Action) {
		if (!this._activated) {
			this._activateTimeline(true);
		}
		if (this._parallel) {
			this._parallel.actions.push(action);
			this._parallel = null;
		} else {
			this.queue.push(action);
		}
		action.frame = 0;

		action.added_to_timeline.fire({timeline: this});

		return this;
	}

	action(params:any) {
		return this.add(new Action(params));
	}

	tween(params:any) {
		return this.add(new Tween(params));
	}

	clear() {
		for (var i = 0, len = this.queue.length; i < len; i++) {
			this.queue[i].removed_from_timeline.fire({timeline:this});
		}
		this.queue = [];
		this._deactivateTimeline();
		return this;
	}

	skip(frames:number) {
		var e:any = {}
		if (this.isFrameBased) {
			e.elapsed = 1;
		} else {
			e.elapsed = frames;
			frames = 1;
		}
		while (frames--) {
			this.tick(e);
		}
		return this;
	}

	pause() {
		if (!this.paused) {
			this.paused = true;
			this._deactivateTimeline();
		}
		return this;
	}

	resume() {
		if (this.paused) {
			this.paused = false;
			this._activateTimeline();
		}
		return this;
	}

	loop() {
		this.looped = true;
		return this;
	}

	unloop() {
		this.looped = false;
		return this;
	}

	delay(time:number) {
		this.add(new Action({
			time: time
		}));
		return this;
	}

	then(func:Function) {
		var action = new Action({time:0});
		action.action_tick.handleInsert(0, action, (e:ActionTickEventArgs) => {
			func.call(this.entity, e);
		});
		this.add(action);
		return this;
	}

	exec(func:Function) {
		this.then(func);
	}

	frame(wait:any, frame?:number[]) {
		var s = <Sprite>this.entity;
		if (frame == undefined) {
			this.then(() => {s.frame = wait;})
		} else {
			this.delay(wait).then(() => { s.frame = frame; });
		}
		return this;
	}

	fno(wait:number, fno?:number) {
		var s = <Sprite>this.entity;
		if (fno == undefined) {
			this.then(() => {s.fno = wait;})
		} else {
			this.delay(wait).then(() => { s.fno = fno; });
		}
		return this;
	}

	cue(cue:any) {
		var ptr = 0;
		for (var frame in cue) {
			var f = parseInt(frame);
			if (cue.hasOwnProperty(frame)) {
				this.delay(f - ptr);
				this.then(cue[frame]);
				ptr = f;
			}
		}
	}

	repeat(func:Function, time:number) {
		var action = new Action({time:time});
		action.action_tick.handle(action, (e:ActionTickEventArgs) => {
			func.call(action, e);
		});
		return this;
	}

	and() {
		var last = this.queue.pop();
		if (last instanceof ParallelAction) {
			this._parallel = <ParallelAction>last;
			this.queue.push(last);
		} else {
			var parallel = new ParallelAction();
			parallel.actions.push(last);
			this.queue.push(parallel);
			this._parallel = parallel;
		}
		return this;
	}

	waitUntil(func:Function) {
		var action = new Action();
		action.action_start = new Trigger();
		//action.action_start.handle(action, func);
		action.action_tick.handle(action, (e:ActionTickEventArgs) => {
			if (func.call(action, e))
				this.next(0);
		});
		this.add(action);
		return this;
	}

	moveTo(x:number, y:number, time:number, easing?:Function) {
		return this.tween({
			x: x,
			y: y,
			time: time,
			easing: easing
		});
	}

	moveX(x:number, time:number, easing?:Function) {
		return this.tween({
			x: x,
			time: time,
			easing: easing
		});
	}

	moveY(y:number, time:number, easing?:Function) {
		return this.tween({
			y: y,
			time: time,
			easing: easing
		});
	}

	moveBy(x:number, y:number, time:number, easing?:Function) {
		return this.tween({
			x: function() {
				return this.x + x;
			},
			y: function() {
				return this.y + y;
			},
			time: time,
			easing: easing
		});
	}

	fadeTo(opacity:number, time:number, easing?:Function) {
		this.tween({
			globalAlpha: opacity,
			time: time,
			easing: easing
		});
		return this;
	}

	fadeIn(time:number, easing?:Function) {
		return this.fadeTo(1, time, easing);
	}

	fadeOut(time:number, easing?:Function) {
		return this.fadeTo(0, time, easing);
	}

	hide() {
		return this.then(function() {
			this.setDrawOption("globalAlpha", 0);
		});
	}

	show() {
		return this.then(function() {
			this.setDrawOption("globalAlpha", 1);
		});
	}

	resizeTo(size:number, time:number, easing?:any) {
		if (typeof easing === "number") {
			return this.tween({
				width: arguments[0],
				height: arguments[1],
				time: arguments[2],
				easing: arguments[3]
			});
		}
		return this.tween({
			width: size,
			height: size,
			time: time,
			easing: easing
		});
	}
	resizeBy(size:number, time:number, easing?:any) {
		if (typeof easing === "number") {
			return this.tween({
				width: function() {
					return this.width + arguments[0];
				},
				height: function() {
					return this.height + arguments[1];
				},
				time: arguments[2],
				easing: arguments[3]
			});
		}
		return this.tween({
			width: function() {
				return this.width + size;
			},
			height: function() {
				return this.height + size;
			},
			time: time,
			easing: easing
		});
	}

	scaleTo(scale:number, time:number, easing?:any) {
		if (typeof easing === "number") {
			return this.tween({
				scale: {x: arguments[0], y: arguments[1]},
				time: arguments[2],
				easing: arguments[3]
			});
		}
		return this.tween({
			scale: {x: scale, y: scale},
			time: time,
			easing: easing
		});
	}

	scaleBy(scale:number, time:number, easing?:any) {
		if (typeof easing === "number") {
			return this.tween({
				scale: function() {
					var _scale = this.getDrawOption("scale");
					return {
						x: _scale.x * arguments[0],
						y: _scale.y * arguments[1]
					}
				},
				time: arguments[2],
				easing: arguments[3]
			});
		}
		return this.tween({
			scale: function() {
				var _scale = this.getDrawOption("scale");
				return {
					x: _scale.x * scale,
					y: _scale.y * scale
				}
			},
			time: time,
			easing: easing
		});
	}

	rotateTo(deg:number, time:number, easing?:Function) {
		return this.tween({
			rotate: deg,
			time: time,
			easing: easing
		});
	}

	rotateBy(deg:number, time:number, easing?:Function) {
		return this.tween({
			rotate: function() {
				return this.getDrawOption("rotate") + deg;
			},
			time: time,
			easing: easing
		});
	}

	removeFromScene() {
		return this.then(function() {
			this.remove();
		});
	}
}
Timeline.prototype.isFrameBased= false;
