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

public class PlayerController : MonoBehaviour {
	//VAR
	public float maxSpeed = 10f;
	bool facingRight = true;

	Animator anim;
	Rigidbody2D rigid2D;

	Vector2 respawn;

	bool grounded = false;
	public Transform groundCheck;
	float groundRadius = 0.2f;
	public LayerMask whatIsGround;
	public float JumpForce = 700f;
	public float fallMultiplier = 2.5f;

	PlayAudio soundMan;

	void Awake()
	{
		rigid2D = GetComponent<Rigidbody2D> ();

		respawn = this.transform.position;

		soundMan = GameObject.FindObjectOfType<PlayAudio> ();
	}
	 
	// Use this for initialization
	void Start () {
		anim = GetComponent<Animator> (); 
		rigid2D = GetComponent<Rigidbody2D> ();

		respawn = this.transform.position;

        GameObject[] lightFogs = GameObject.FindGameObjectsWithTag("LightFog");
        if (lightFogs.Length > 0)
        {
            lightFogs[0].GetComponent<LightFogManager>().AddLightTarget(gameObject);
        }
    }//end start

	void FixedUpdate () {
		//Checking for ground
		grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
        anim.SetBool("isJumping", !grounded);

        //Handles simple movement Left and Right
        float hAxis = Input.GetAxis ("Horizontal");
        anim.SetBool("isMoving", Mathf.Abs(hAxis) > 0.5f);

		rigid2D.velocity = new Vector2(hAxis * maxSpeed, rigid2D.velocity.y);

		//Is seeing which way the player is moving to determin where it should be looking. 
		if(hAxis > 0 && !facingRight){
			Flip();
		}
		else if(hAxis < 0  && facingRight){
			Flip();
		}
	}//end fixedupdate

	void Update(){
		if (grounded && Input.GetKeyDown (KeyCode.Space)) {
			rigid2D.AddForce (new Vector2 (0, JumpForce));
			soundMan.PlaySounds (6);
		}

		if (rigid2D.velocity.y < 0) {
			rigid2D.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
		}
	}//end update

	void Flip(){
		facingRight = !facingRight; 
		Vector3 theScale = transform.localScale;
		theScale.x *= -1;
		transform.localScale = theScale;
	}//end flip

	void OnTriggerEnter2D (Collider2D c)
	{
		if (c.tag == "Killzone") {
			this.transform.position = respawn;
			soundMan.PlaySounds (2);
		}
		if (c.tag == "Checkpoint") {
			respawn = c.transform.position;
			soundMan.PlaySounds (0);
		}
	}

    void OnDestroy()
    {
        GameObject[] lightFogs = GameObject.FindGameObjectsWithTag("LightFog");
        if (lightFogs.Length > 0)
        {
            lightFogs[0].GetComponent<LightFogManager>().RemoveLightTarget(gameObject);
        }
    }// end OnDestroy
}//end class