using UnityEngine;
using System.Collections;

public class player_movement : MonoBehaviour {

	Rigidbody2D r_body;
	Animator anim;

	public GameObject groundcheck;

	private bool isGrounded = true;
	private bool facing_right = true;

	public float jump_force;
	public float move_force;
	public float max_speed;
	public GameObject sword;


	void Start () {
	
		r_body = GetComponent<Rigidbody2D>();
		anim = GetComponent<Animator>();
	}
	
	void Update () {

		float h = Input.GetAxis("Horizontal");

		if(Input.GetButtonDown("Jump") && isGrounded)
		{
			r_body.AddForce(new Vector2(0, jump_force));
			anim.SetBool("Jump", true);
		}
		else
		{
			anim.SetBool ("Jump", false);
		}

		if(Input.GetButtonDown("Fire1"))
		{
			anim.SetTrigger("Attack");
			r_body.velocity = Vector2.zero;

			sword.GetComponent<Collider2D>().enabled = true;
			Invoke ("DisableSword",0.5f);
		}

		r_body.AddForce(new Vector2(move_force * h, 0));

		anim.SetFloat("Speed", Mathf.Abs (h));


		if(r_body.velocity.x > max_speed)
		{
			r_body.velocity = new Vector2(max_speed, r_body.velocity.y);
		}
		else if(r_body.velocity.x < max_speed * -1)
		{
			r_body.velocity = new Vector2(max_speed * -1, r_body.velocity.y);
		}

		if(facing_right && h < 0)
		{
			Flip();
		}
		else if(!facing_right && h > 0)
		{
			Flip ();
		}

		// check grounded
		RaycastHit2D hit = Physics2D.Linecast(transform.position, groundcheck.GetComponent<Transform>().position, 1 << LayerMask.NameToLayer("Platform"));

		if(hit.collider != null)
		{
			isGrounded = true;
		}
		else
			isGrounded = false;

		Debug.Log (isGrounded);
	}

	void Flip()
	{
		facing_right = !facing_right;

		Vector3 tmp = transform.localScale;
		tmp.x = tmp.x * -1;

		transform.localScale = tmp;
	}

	void DisableSword ()
	{
		sword.GetComponent<Collider2D> ().enabled = false;
	}
}
