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

public class Player : MonoBehaviour {

	public float jumpForce = 200;
	public float moveForce = 3f;
	public float maxVelocity = 10f;
	public AudioClip jumpAudio;
	public AudioClip deadAudio;
	public AudioClip teleportAudio;
	public AudioClip spawnAudio;
	private bool promote = false;
	private bool restartPlease = false;
	public Sprite deadTexture;
	public GameObject ovalDeadObject;

	public Camera playerCamera;
	public Vector3 initPosition;
	private RotationRatata level;
	public string nextScene;

	private AudioSource audioS;
	private string FLOOR_TAG = "FLOOR";
	private string HURTS_TAG = "HURTS";
	private string PROMOTION_TAG = "PROMOTION";
	KeyCode upKey;
	KeyCode leftKey;
	KeyCode rightKey;
	Rigidbody2D rigid;
	private bool started = false;
	Vector3 jumpVector;
	private float jumpCoolDown = 0.1f;
	private float lastTimeJump = 0f;
	private float moveCollisionCooldown = 0.1f;
	private float lastTimeCollision = 0f;
	private float jumpVectorMaxMoveY = 0.1f;

	private float changeSceneCooldown = 0;
	private float changeLevelTime = 1;

	// Use this for initialization
	void Start () {
		Time.timeScale = 1.0f;
		initPosition = transform.position;
		rigid = GetComponent<Rigidbody2D> ();
		upKey = KeyCode.UpArrow;
		leftKey = KeyCode.LeftArrow;
		rightKey = KeyCode.RightArrow;
		jumpVector = -Vector2.one;
		audioS = GetComponent<AudioSource> ();
		audioS.PlayOneShot (spawnAudio);
		level = transform.parent.GetComponent<RotationRatata> ();
	}

	// Update is called once per frame
	void Update () {
		
		if (changeSceneCooldown > changeLevelTime) {
			if (restartPlease) {
				SceneManager.LoadScene (SceneManager.GetActiveScene().name);
			} if (promote) {
				SceneManager.LoadScene (nextScene);
			}
		}

		if (restartPlease || promote) {
			Time.timeScale = 0.3f;
			changeSceneCooldown += Time.deltaTime;
		} else {

			if (Input.anyKeyDown && !started) {
				level.LetsTheGameBegin ();
				started = true;
			}

			if (Input.GetKeyDown (KeyCode.Escape)) {
				Application.Quit ();
			}

			playerCamera.transform.position = new Vector3 (transform.position.x, transform.position.y, playerCamera.transform.position.z);

			if (Input.GetKey (upKey) && jumpVector.y >= 0) {
				float currentTime = Time.time;
				float timeDelta = currentTime - lastTimeJump;
				if (timeDelta > jumpCoolDown) {
					lastTimeJump = currentTime;
					float raycastCoefficient = 0.26f;
					RaycastHit2D hit = Physics2D.Raycast (new Vector2 (transform.position.x + jumpVector.x * raycastCoefficient, transform.position.y - jumpVector.y * raycastCoefficient), new Vector2 (jumpVector.x, -jumpVector.y), 0.05f);
					Debug.DrawRay (new Vector2 (transform.position.x + jumpVector.x * raycastCoefficient, transform.position.y - jumpVector.y * raycastCoefficient), new Vector2 (jumpVector.x * 0.1f, -jumpVector.y * 0.1f), Color.black, 5);
					if (hit.collider != null) {
						jumpVector = Vector2.up;
					}
					rigid.AddForce (jumpForce * jumpVector);
					jumpVector = -Vector2.one;
					playSound (jumpAudio);
				}

			}

			if (Input.GetKey (rightKey)) {
				float currentTime = Time.time;
				float timeDelta = currentTime - lastTimeCollision;
				if (jumpVector.y > jumpVectorMaxMoveY || timeDelta > moveCollisionCooldown) {
					rigid.AddForce (new Vector2 (moveForce, 0));
				}
			}

			if (Input.GetKey (leftKey)) {
				float currentTime = Time.time;
				float timeDelta = currentTime - lastTimeCollision;
				if (jumpVector.y > jumpVectorMaxMoveY || timeDelta > moveCollisionCooldown) {
					rigid.AddForce (new Vector2 (-moveForce, 0));
				}
			}

			if (rigid.velocity.x > maxVelocity) {
				rigid.velocity = new Vector2 (maxVelocity, rigid.velocity.y);
			}
			if (rigid.velocity.x < -maxVelocity) {
				rigid.velocity = new Vector2 (-maxVelocity, rigid.velocity.y);
			}
		}
	}

	void OnCollisionEnter2D(Collision2D coll) {
		Debug.Log (coll.gameObject.tag);
	}

	void OnCollisionStay2D(Collision2D coll) {
		if (coll.gameObject.tag == FLOOR_TAG) {
			if (coll.contacts.Length == 1) {
				jumpVector = coll.contacts [0].normal;
			} else {
				throw new UnityException ();
			}
		}
		lastTimeCollision = Time.time;
	}
	void OnCollisionExit2D(Collision2D coll) {
		if (coll.gameObject.tag == FLOOR_TAG) {
			jumpVector = -Vector2.one;
		}
	}
	void OnTriggerEnter2D(Collider2D coll) {
		if (coll.gameObject.tag == HURTS_TAG) {
			KillMe ();
		} else if (coll.gameObject.tag == PROMOTION_TAG) {
			MoveMeToNextLevel ();
		}
	}

	private void MoveMeToNextLevel () {
		audioS.PlayOneShot (teleportAudio);
		promote = true;
	}

	private void KillMe() {
		audioS.PlayOneShot (deadAudio);
		GameObject dead = Instantiate(ovalDeadObject, transform.position, transform.rotation, transform.parent) as GameObject;
		Destroy (GetComponent<SpriteRenderer> ());
		Destroy (rigid);
		Destroy (GetComponent<Collider2D> ());
		restartPlease = true;
	}

	void playSound(AudioClip clip) {
		audioS.PlayOneShot (clip);
	}


}
