using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class PlayerController : MonoBehaviour {

	[SerializeField] [Range(0f,6f)] float speed = 1f;
	Rigidbody2D playerRigidbody;
	float h = 0;
	private int life = 100;
	public int points = 0;

	public bool isFacingRight;
	public int playerID;
	public int controller;
	public bool canShoot;

	public float jumpShortSpeed = 3f;   // Velocity for the lowest jump
	public float jumpSpeed = 6f;          // Velocity for the highest jump
	bool canJump = false;
	bool jumpCheck = false;
	bool jumpCancel = false;

	[Header("DamageObject")]
	public GameObject damageObject;
	public float timeToDesactive=0.1f;
	public float coolDownTime=0.5f;

	public Teams team;

	Animator anim;
	bool jumpAnim;
	bool moveAnim;
	public PlayerNames playerName;
	bool isKilled;

	public float respawnTimer=5;
	private Vector3 startPosition;
	private Vector3 startEulerAngles;

	float v;

	void Awake() {
		canShoot = true;
		anim = GetComponent<Animator>();
		playerRigidbody = GetComponent<Rigidbody2D>();

		startPosition = transform.position;
		startEulerAngles = transform.eulerAngles;
	}

	// Update is called once per frame
	void FixedUpdate () {
		if (GameController.GetCurrentStates () == GameStates.GAME_PLAY) {
			if (!isKilled) {
				float h = Input.GetAxis ("Horizontal" + controller.ToString ());
				Debug.Log (h);
				transform.localScale = new Vector3 (h > 0 ? (Mathf.Abs (transform.localScale.x)) : h < 0 ? (-Mathf.Abs (transform.localScale.x)) : transform.localScale.x, transform.localScale.y, transform.localScale.z);
				isFacingRight = transform.localScale.x > 0;
				Move (h);
				Attack ();
				Move (h);

				if (Input.GetButtonDown ("Jump" + controller) && canJump)   // Player starts pressing the button
				jumpCheck = true;
				if (Input.GetButtonUp ("Jump" + controller) && !canJump)     // Player stops pressing the button
				jumpCancel = true;
				Jump ();

				Animating (h);
			} else {
				anim.SetBool ("IsKilled", isKilled);
			}
		}
	}

	void Attack (){
		if (Input.GetButtonDown ("Fire"+controller) && canShoot) {
			AudioController.PlayPlayerSound (playerName, SoundEffects.ATTACK);
			anim.SetTrigger ("Attack");
			damageObject.SetActive (true);
			StartCoroutine (DesactiveDamager ());
			//GameController.instance.soundWavePool.SpawnAtPosition(playerRigidbody.position).GetComponent<SoundWave>().goingToRight = isFacingRight;
			StartCoroutine (CoolDown());
		}
	}

	public void BeHit(int damage, PlayerController p){
		if(!isKilled){
			AudioController.PlayPlayerSound (playerName, SoundEffects.HIT);
			life -= damage;

			GameController.UpdatePlayerLife (playerID, life);
			if (life <= 0) {
				if (p != null) {
					p.AddScore (10);
				}
				isKilled = true;
				//transform.eulerAngles = new Vector3 (0, 0, 90);
				StartCoroutine(Respawn ());
			}
		}
	}

	void Move(float h)
	{
		playerRigidbody.velocity = new Vector2(h * speed, playerRigidbody.velocity.y);

	}

	void Animating(float h)
	{
//		bool walking = h != 0f;
//		anim.SetBool("IsWalking", walking);
//
//		bool jumping = playerRigidbody.velocity.y != 0f;
//		anim.SetBool("IsJumping", jumping);

		if (Mathf.Abs(playerRigidbody.velocity.y) > 0.1 && !canJump)
		{
			jumpAnim = true;
		}
		else
		{
			if (!canJump) jumpAnim = true;
			else jumpAnim = false;
		}
		//        jumpAnim = playerRigidbody.velocity.y != 0f;
		moveAnim = h != 0f;

		//        bool jumping = playerRigidbody.velocity.y != 0f;
		//        bool walking = h != 0f;

		if (jumpAnim) {
			moveAnim = false;
		}
		anim.SetBool("IsJumping", jumpAnim);
		anim.SetBool("IsWalking", moveAnim);
		anim.SetBool ("IsKilled", isKilled);

	}

	void Jump()
	{
		Vector2 pos = transform.position;
		pos.y -= .8f;

		Debug.DrawRay (pos, new Vector3 (0, -0.2f, 0));
		RaycastHit2D hit=Physics2D.Raycast(pos,Vector2.down,0.2f);

		if(hit.collider!=null){
			if(hit.collider.tag=="Ground"){
				canJump=true;
			}else{
				canJump=false;
			}
		}else{
			canJump=false;
		}
			
		// Normal jump (full speed)
		if (jumpCheck)
		{
			playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, jumpSpeed);
			jumpCheck = false;
		}
		// Cancel the jump when the button is no longer pressed
		if (jumpCancel)
		{
			if (playerRigidbody.velocity.y > jumpShortSpeed)
				playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, jumpShortSpeed);
			jumpCancel = false;
		}
	}

	public void SetJoystick(Joysticks js)
	{
		controller = (int)js; // Controller = 0 is keyboard
	}

	public void SetTeam(/*Teams team*/)
	{

	}

//	void OnTriggerEnter2D()
//	{
//		canJump = true;
//	}
//	void OnTriggerExit2D()
//	{
//		canJump = false;
//	}

	public void AddScore(int amount) {
		points += amount;
		GameController.UpdatePlayersPoints (playerID,points);
	}

	IEnumerator DesactiveDamager(){
		yield return new WaitForSeconds (timeToDesactive);
		damageObject.SetActive (false);
	}

	IEnumerator CoolDown(){
		canShoot = false;
		yield return new WaitForSeconds (coolDownTime);
		canShoot = true;
	}

	IEnumerator Respawn(){
		yield return new WaitForSeconds (respawnTimer);
		isKilled = false;
		transform.position = startPosition;
		transform.eulerAngles = startEulerAngles;
		life = 100;
		GameController.UpdatePlayerLife (playerID, life);
	}
		
}
