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

public class PlayerCollision : MonoBehaviour {

	Vector3 startSize;
	public Vector3 deadSize;
	public float invincibilityTime = 1f;
	public float invincibilityTimer = 0f;
	public float damageScale = .01f;
	public Transform targetToScale;
	float damage = 0f;
	float pushForce = 0f;
	Vector3 pushDirection;
	public AudioSource aSource;
	public AudioClip asteroidHit;
	float audioCooldown = 0f;

	void Start(){
		startSize = targetToScale.localScale;
	}

	void Update(){
		if(invincibilityTimer > 0f)
			invincibilityTimer-= Time.deltaTime;
		if(invincibilityTimer < 0f)
			invincibilityTimer = 0f;

		if(GlobalScript.orbiting){
			pushForce = 0f;
			pushDirection = Vector3.zero;
		}

		if(pushForce > 0f){
			transform.position += pushDirection * Time.deltaTime;
			pushForce -= Time.deltaTime;
		}
	}

	public void Collide(OrbitScript other){
		if(GlobalScript.finale)
			return;

		if(audioCooldown > 0f){
			audioCooldown -= Time.deltaTime;
		}

		if(other.gameObject.tag == "Planet"){
			/*float force = other.speed / 10f;
			if(pushForce < 0f){
				pushDirection = Vector3.zero;
				pushForce = 0f;
			}
			pushDirection += (transform.position - other.transform.position).normalized;
			pushForce += force;*/
			if(GlobalScript.attachDelay <= 0f)
				gameObject.SendMessage("StartOrbit", other.transform);
		}else if(other.gameObject.tag == "Asteroid"){
			float force = other.speed / 10f;

			if(invincibilityTimer <= 0f){
				invincibilityTimer = invincibilityTime;
				//Debug.Log((force / 8.5f) * damageScale);
				damage += (force / 6.5f) * damageScale;
				targetToScale.localScale = Vector3.Lerp(startSize, deadSize, damage);
			}

			if(pushForce < 0f){
				pushDirection = Vector3.zero;
				pushForce = 0f;
			}

			pushDirection += (transform.position - other.transform.position).normalized;
			pushForce = 1f;
			float volume = 1f;
			if(invincibilityTimer <= 0f)
				volume = .5f;

			if(audioCooldown <= 0f){
				aSource.PlayOneShot(asteroidHit, volume);
				audioCooldown += 1f;
			}

			if(damage >= .5f){
				targetToScale.localScale *= 0.2f;
				GlobalScript.EndShattered();
			}
		}
	}
}
