using UnityEngine;
using System.Collections;

public class GravWave : MonoBehaviour {

	public int MIN_SPEED = 400;
	public int MAX_SPEED = 600;

	public float mag;
	public Vector3 dir;
	public GameObject player;
	public GameObject truePlayer;

	public bool firstCollision;
	public bool follow;

	public GameObject skimmer;

	public bool goThrough;

	public AudioSource audio;



	void Start() {
		audio = GetComponent<AudioSource>();
		audio.loop = true;
		audio.Play(0);
		goThrough = true;
		firstCollision = true;
		follow = false;
		transform.Rotate(transform.right, 90f);
		mag = Random.Range(MIN_SPEED, MAX_SPEED);
		StartCoroutine(die());
		truePlayer = GameObject.Find("ShipStandin");
	}

	void Update() {
		//Debug.Log(audio.isPlaying);
		//Debug.Log(audio.volume);
		if (!follow) {
			transform.Translate(dir * mag * Time.deltaTime);
			transform.position = new Vector3(transform.position.x, 0, transform.position.z);
		}
		else {
			transform.position = skimmer.transform.position;
		}
	}

	public IEnumerator die() {
		yield return new WaitForSeconds(3f);
		if (goThrough) {
			Destroy(gameObject);
		}
	}

	public IEnumerator dieSooner() {
		float timeLeft = 15f;
		while (timeLeft > 0) {
			timeLeft -= 0.1f;
			yield return null;
			transform.localScale = 0.9f * transform.localScale;
		}
		Destroy(gameObject);
	}

	void OnTriggerEnter(Collider other) {
		if (firstCollision) {
			if (other.tag == "Skimmer") {
				goThrough = false;
				follow = true;
				skimmer = other.gameObject;
				transform.parent = skimmer.transform;
				truePlayer.GetComponent<PlayerController>().waveBoost += 150;
				truePlayer.GetComponent<PlayerController>().Fuel += 50;
				StartCoroutine(dieSooner());

				Skimmer.side side = other.GetComponent<Skimmer>().flip;
				if (side == Skimmer.side.RIGHT) {
					truePlayer.GetComponent<PlayerController>().waveOffset = -truePlayer.transform.right * mag;
				}
				else {
					truePlayer.GetComponent<PlayerController>().waveOffset = truePlayer.transform.right * mag;
				}

				firstCollision = false;
			}
			else if (other.tag == "Player") {
				goThrough = false;
				truePlayer.GetComponent<PlayerController>().waveBoost = -100;
				StartCoroutine(dieSooner());
				truePlayer.GetComponent<PlayerController>().Fuel -= 25;
				firstCollision = false;
			}
		}
		if (other.tag == "Debris") {
			goThrough = false;
			StartCoroutine(dieSooner());
		}
	}
}
