using UnityEngine;
using System.Collections;

public class playerController : MonoBehaviour 
{
	//Player variables.
	public float playerHealth;
	public float playerEnergy;
	public float energyRate;
	public bool discharged;
	public bool dead;
	
	//Movement variables.
	public float defaultSpeed;
	public float boostSpeed;
	public float boostDrain;
	private Vector3 move = Vector3.zero;
	public CharacterController control;
	private Vector3 startPosition;
	private float activateBoost;
	private float HorizontalMove;
	private float VerticalMove;
	private float playerSpeed;
	
	//Projectile variables;
	public GameObject playerProjectile;
	public float bulletOffset;
	public float bulletHeight;
	public float bulletSidePos;
	public float chargeSpeed;
	public float chargeLevel;
	public float chargeLimit;
	public float chargeDamage;

    public togglePsychosis togglePsychosisScript;
//    public HingeJoint hinge;
//    JointMotor motor;

	public GameObject basicAttackSphere;
	float basicAttackSphereRadius;
	public float basicAttackDamage;
	public bool twinStick;

    void Awake()
    {
//        hinge = GetComponent<HingeJoint>();
//        motor = hinge.motor;
        //motor.targetVelocity = 10.0f;
    }
	// Use this for initialization
	void Start () 
	{
        //hinge = this.gameObject.GetComponent<HingeJoint>();
		control = GetComponent<CharacterController>();
		startPosition = transform.position;  
		basicAttackSphereRadius = basicAttackSphere.GetComponent<SphereCollider> ().radius;

	}

    void swingSword()
    {
		Collider[] hitColliders = Physics.OverlapSphere(basicAttackSphere.transform.position, basicAttackSphereRadius);
		int i = 0;
		while (i < hitColliders.Length) 
		{
			if (hitColliders[i].gameObject.GetComponent<S_enemyLevel>())
			{
				hitColliders[i].gameObject.GetComponent<S_enemyLevel>().enemyHealth =- basicAttackDamage;
				i++;
			}
		}
        //Debug.Log("swingsowrd");
        //motor.force = 100;
        //motor.targetVelocity = 100.0f;
        //gameObject.GetComponent<HingeJoint>().motor = this.motor;
        //hinge.motor.force = 100;
    }

	// Update is called once per frame
	void Update () 
	{
		//Debug.Log ("axis " + Input.GetAxis("Horizontal"));
		basicAttackSphere.transform.position = this.transform.position + new Vector3(Input.GetAxis ("Horizontal") * 1.5f, .4f, Input.GetAxis ("Vertical") * 1.5f);
		if (twinStick) 
		{
			basicAttackSphere.transform.position = this.transform.position + new Vector3 (Input.GetAxis ("ArrowHorizontal") * 1.5f, .4f, Input.GetAxis ("ArrowVertical") * 1.5f);
		}
		//posTemp.Set (Input.GetAxis ("Horizontal") * 1.25f, Input.GetAxis ("Vertical") * 1.25f);
        if (Input.GetKeyDown(KeyCode.Space))
        {
            swingSword();
        }
		else if (Input.GetButtonDown("BasicAttack"))
        {
			swingSword();
		}
        
		//Set player energy range and recharge rate.
		playerEnergy = Mathf.Clamp (playerEnergy, 0, 100);
		playerEnergy += Time.deltaTime * energyRate;
		
		if (playerEnergy <= 1)
			discharged = true;
		
		if (playerEnergy >= 100)
			discharged = false;
		
	#region Movement 
		
		if (dead == false)
		{
			//Controls movement.
			
			//Boost.
			activateBoost = Input.GetAxis("Boost");
			
			if (activateBoost < -0.1f  && discharged == false || activateBoost > 0.1f && discharged == false)
			{
				playerSpeed = boostSpeed;
				playerEnergy -= Time.deltaTime * boostDrain;
			}
			else if (activateBoost > -0.1f && activateBoost < 0.1f || discharged == true)
			{
				playerSpeed = defaultSpeed;	
			}
		
		
			//Movement.				
			move = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
			move.Normalize();
			control.SimpleMove (move * playerSpeed);
		

			//Charges Projectile.
			if (Input.GetButton("ForwardFire") && chargeLevel < chargeLimit)	
			{	
				chargeLevel += Time.deltaTime * chargeSpeed;
			}
			
			else if (Input.GetButton("LeftFire") && chargeLevel < chargeLimit)	
			{	
				chargeLevel += Time.deltaTime * chargeSpeed;
			}
			
			else if (Input.GetButton("RightFire") && chargeLevel < chargeLimit)	
			{	
				chargeLevel += Time.deltaTime * chargeSpeed;
			}
			
			else if (Input.GetButton("BackFire") && chargeLevel < chargeLimit)	
			{	
				chargeLevel += Time.deltaTime * chargeSpeed;
			}
		}
	#endregion
		
	#region Projectiles
	if (dead == false)
	{
	//Fires projectile.
		//Forward fire.
		if (Input.GetButtonUp("ForwardFire") && discharged == false)
		{                                                                               
			Vector3 position = new Vector3(transform.position.x, transform.position.y + bulletHeight, transform.position.z + bulletOffset);
			
			projectileFire();

			Instantiate(playerProjectile, position, Quaternion.identity);	
				
			projectileReset();
		}
			
		//Left fire.
		else if (Input.GetButtonUp("LeftFire") && discharged == false)
		{                                                                               
			Vector3 position = new Vector3(transform.position.x, transform.position.y + bulletHeight, transform.position.z + bulletOffset);
			
			projectileFire();
				
			Instantiate(playerProjectile, position, Quaternion.LookRotation(Vector3.left, Vector3.up));	
				
			projectileReset();
		}                                                         //Ammount to offset bullets.
		
		//Right fire.
		else if (Input.GetButtonUp("RightFire") && discharged == false)
		{                                                                               //Ammount to offset bullets.
			Vector3 position = new Vector3(transform.position.x, transform.position.y + bulletHeight, transform.position.z+ bulletOffset);
			
			projectileFire();
				
			Instantiate(playerProjectile, position, Quaternion.LookRotation(Vector3.right, Vector3.up));	
				
			projectileReset();
		}
		
		//Back fire.
		else if (Input.GetButtonUp("BackFire") && discharged == false)
		{   Vector3 position = new Vector3(transform.position.x, transform.position.y + bulletHeight, transform.position.z + bulletOffset);
			
			projectileFire();
				
			Instantiate(playerProjectile, position, Quaternion.LookRotation(Vector3.back, Vector3.up));	
				
			projectileReset();
		}
	}
		
		
	}
	
		void projectileFire()
	{
		if(chargeLevel > 2f && discharged == false)
			{
				chargeDamage = 3f;
				playerProjectile.transform.localScale = new Vector3(0.8f, 0.8f, 0.8f);
				playerProjectile.audio.pitch = 0.75f;
				playerProjectile.audio.volume = 1f;
				playerEnergy -= 40;
			}
				
			else if (chargeLevel > 0.75f && discharged == false)
			{
				chargeDamage = 2f;
				playerProjectile.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
				playerProjectile.audio.pitch = 1f;
				playerProjectile.audio.volume = 0.75f;
				playerEnergy -= 20;
			}	
			
			else if (chargeLevel > 0f && discharged == false)
			{
				chargeDamage = 1f;
				playerProjectile.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
				playerProjectile.audio.pitch = 1.25f;
				playerProjectile.audio.volume = .5f;
				playerEnergy -= 3;
			}
		
			
	}
	
	void projectileReset()
	{
		playerProjectile.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
		chargeLevel = 0f;
		playerProjectile.audio.pitch = 1.25f;
		playerProjectile.audio.volume = 0.5f;
	}
	
	#endregion
	
	void OnTriggerEnter (Collider other)
	{
		//If player gets hit by an enemy.
		if (other.gameObject.tag == "enemy")
		{
            togglePsychosisScript.switchPhyschosis();
			float damage = other.gameObject.GetComponent<S_enemyLevel>().enemyAttack;
			playerHealth -= damage;
			if (playerHealth <= 0)
				StartCoroutine(destroyMech());
		}
		
		
		
			if (other.gameObject.tag == "eProjectile")
		{
            togglePsychosisScript.switchPhyschosis();
			playerHealth--;
			if (playerHealth <= 0)
				StartCoroutine(destroyMech());
		}
		
	}
	
		void OnCollisionEnter (Collision other)
	{
        Debug.Log("isHappening");
		//If player gets hit by an enemy.
		if (other.gameObject.tag == "enemy")
		{
            togglePsychosisScript.switchPhyschosis();
            Debug.Log("isHappening");
			float damage = other.gameObject.GetComponent<S_enemyLevel>().enemyAttack;
			playerHealth -= damage;
			if (playerHealth <= 0)
				StartCoroutine(destroyMech());
		}
		
		
		
			if (other.gameObject.tag == "eProjectile")
		{
            togglePsychosisScript.switchPhyschosis();
            Debug.Log("isHappening22");
			playerHealth--;
			if (playerHealth <= 0)
				StartCoroutine(destroyMech());
		}
		
	}
	
	
	IEnumerator destroyMech()
	{
		gameObject.renderer.enabled = false;
		transform.position = startPosition;
		dead = true;
		yield return new WaitForSeconds(1.5f);
		Application.LoadLevel(1);
	}
	


}
