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

public abstract class Surfer : MonoBehaviour {
	//public fields
	public InputHandler handler;
	public GameObject particle;
	public bool inPlay = false;
	public GameObject crown;

	//private fields
	private Collider localCol;
	private Rigidbody rgd;
	private float turnCoef = 1.0f;
	private Vector3 steeringVector;
	private float baseSpeed = 15.0f;
	private bool canJump = true;
	private float jumpSize = 1.0f;
	private int drag = 1;
	private int breakPower = 4;

	private Vector3 startPos;

	//return player to spawn, disable controls
	public void Eliminate (){
		if (!inPlay)
			return;
		inPlay = false;
		Instantiate (particle, transform.position, Quaternion.identity);
		StartCoroutine (Death ());
	}

	IEnumerator Death(){
		yield return new WaitForSeconds (1.5f);
		GameManager.instance.PlayerEliminated ();
		rgd.velocity = Vector3.zero ;
		transform.rotation = Quaternion.identity;
		rgd.useGravity = false;
		localCol.isTrigger = true;
		rgd.isKinematic = true;
		transform.position = startPos;
	}

	//Initialization
	void Start () {
		jumpSize = 2;
		startPos = transform.position;
		localCol = GetComponent<Collider> ();
		rgd = GetComponent<Rigidbody> ();
		steeringVector = new Vector3 (0, turnCoef, 0);
	}
	
	//Called once per FIXEDframe
	void FixedUpdate () {
		if (inPlay) {
			rgd.AddRelativeForce (Vector3.forward*baseSpeed);
			if (handler.GetButton (0))
				Steer (-1);
			else if (handler.GetButton (1))
				Steer (1);
			if (handler.GetButton (2))
				Jump ();
			rgd.drag = handler.GetButton (3) ? breakPower : drag;

		}
	}

	void Update(){
		if (inPlay) {
			if (GameManager.instance.playersAlive <= 1)
			if (GameManager.instance.Win ()) {
				crown.SetActive (true);
				StartCoroutine (disableCrown ());
			}
		}
	}

	IEnumerator disableCrown(){
		yield return new WaitForSeconds (2.5f);
		crown.SetActive(false);
	}

	//Aplly the steering
	void Steer(int dir){
		transform.Rotate(steeringVector * dir);
	}

	// Start the game
	void Play(){
		localCol.isTrigger = false;
		GameManager.instance.Prepare ();
	}

	//Apply the jumpm force and trigger the cooldown
	void Jump(){
		if (!canJump)
			return;
		rgd.AddForce (Vector3.up * 5 * jumpSize, ForceMode.Impulse);
		canJump = false;
		Invoke ("TriggerJumpCooldown", jumpSize);
	}

	//Called in the end of cooldown
	void TriggerJumpCooldown(){
		canJump = true;
	}

	//Used to start the game when hit by the wave
	void OnTriggerEnter (Collider col){
		if (col.name == "WaveTop" && !inPlay) {
			if (handler == null)
				Destroy (gameObject);
			rgd.isKinematic = false;
			rgd.AddForce (Vector3.up * 7.5f, ForceMode.Impulse);
			rgd.useGravity = true;
			inPlay = true;
			Invoke ("Play", 1f);
		}
	}
			
}
