package ;

import flixel.FlxG;
import flixel.FlxSprite;
import flixel.util.FlxColor;
import flixel.*;
import openfl.Assets;
import flixel.tweens.FlxTween;
import flixel.tweens.FlxEase;
import flixel.util.FlxTimer;
import flixel.text.FlxText;
import flixel.util.FlxColor;
import flixel.util.FlxRandom;

class Player extends FlxSprite
{

	var touched:Bool = false;
	public var startY:Float;
	private var jumping = false;
	public var keyText:FlxText;
	private var jump_power:Float = 0;
	private var max_jump_power:Float = 350;
	private var max_jump_height = FlxG.height * 0.75;
	public var key_is_down = false;
	public var key_was_down = false;
	public var pose = 0;

	
    public function new(X:Float=0, Y:Float=0, _keyText:FlxText)
    {
        super(X, Y);

        startY = Y;

        this.acceleration.y = 2250;

        keyText = _keyText;
		loadGraphic(Reg.assets_dir + "player.png", true, 50, 50);
		animation.add("standing", [0]);
		animation.add("jumping", [2]);
		animation.add("pose0", [2]);
		animation.add("pose1", [3]);
		animation.add("pose2", [4]);
		animation.add("pose3", [5]);
	}

	override public function kill()
	{
		var rand = FlxRandom.intRanged( 1, 3 );
		FlxG.sound.play("hit" + rand);
		FlxG.camera.shake(0.01, 0.2);		
		super.kill();
	}

	override public function revive()
	{
		this.y = startY;
		this.velocity.x = 0;
		this.velocity.y = 0;
		super.revive();
	}

	public function key_down()
	{
		if (!jumping && y > startY + 1) 
		{
			jump_power = max_jump_power;
			jumping = true;
			pose = -1;
			animation.play("jumping");
			y -= 5;
			FlxG.sound.play("jump");
		}
		this.velocity.y -= jump_power;		

		key_is_down = true;
	}

	public function change_pose()
	{
		if (jumping)
		{
			pose ++;			
			if (pose > 3) {
				pose = 0;
			}		
			animation.play("pose" + pose);
			this.scale.x = 1.1;
			this.scale.y = 1.1;
			FlxTween.tween(this.scale, { x:1, y:1 }, 0.2, { ease: FlxEase.quadOut, complete: untouch });
			FlxG.sound.play("select");

			//jumping = false;
		}
	}

	public function landed()
	{
		if (jumping)
		{
			jumping = false;
			animation.play("standing");
			pose = 0;
		}
	}

	public function touch()
	{
		if (!touched) {
			touched = true;
			this.scale.x = 1.2;
			this.scale.y = 1.2;			
			FlxTween.tween(this.scale, { x:1 }, 0.5, { ease: FlxEase.quadOut, complete: untouch });
			FlxTween.tween(this.scale, { y:1 }, 0.5, { ease: FlxEase.quadOut});
			FlxG.sound.play("success");
		}
	}

	private function untouch(Tween:FlxTween)
	{
		touched = false;
	}
	
	override public function update():Void 
	{				
		super.update();

		if (jumping)
		{
			jump_power *= 0.8;
		}
		//scale.x = 1 + jump_power / 1000;
		//scale.y = 1 - jump_power / 1000;

		if (key_is_down && !key_was_down)
		{
			change_pose();
		}

		if (key_was_down && !key_is_down) {
			//key_up();
			key_was_down = false;
		}
	}
}