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

public class FanWave : MonoBehaviour {

	public GameObject[] fanVariations;
	public int initalFan;
	public float fanOffsetX;
	public float amplitude;
	public Vector3 initOffset;
	public int raisingHands;

	bool jumping;

	public int fanDeleted;

	List<GameObject> fanPool;
	int randomLimit;
	int currIndex;
	float yOffset;

	int deletedObjects;
	int currJumping;

	public int deletedMult;


	public void upHands(Vector3 position)
	{
		//Debug.Log("UPHANDS");
		currJumping = findNearest(position);
		StartCoroutine(up());
	}

	int findNearest(Vector3 position) {
		float minDistance = Mathf.Infinity;
		int candidate = 0;
		for(int i=0; i<fanPool.Count; i++) {
			float distance = Vector3.Distance(fanPool[i].transform.position, position);
			if(distance < minDistance) {
				minDistance = distance;
				candidate = i;
			}
		}
		return candidate;
	}
		
	void Awake () {
		randomLimit = fanVariations.Length;
		fanPool = new List<GameObject>();
		currIndex = 0;
		deletedObjects = 0;
		deletedMult = 1;
		fanDeleted = 0;
		generateFirstNElements(initalFan);
	}

	void Update () {
		if(Camera.main.gameObject.transform.position.x > fanPool[0].transform.position.x+15f) {
			GameObject.Destroy(fanPool[0]);
			fanPool.RemoveAt(0);
			deletedObjects++;
			fanDeleted = fanDeleted + (1*deletedMult);
			generateNextElement();
		}
		yOffset -= Mathf.Pow(Time.deltaTime, .6f);
		yOffset = Mathf.Clamp(yOffset, 0f, 100f);
		float _yOffset = yOffset;
		if(yOffset == 0f) jumping = true;
		for(int i=0; i<fanPool.Count; i++) {
			if(jumping) {
				if (i == currJumping) {
					_yOffset = yOffset;
				}
				else if(i > currJumping-(raisingHands*.5f) && i < currJumping+(raisingHands*.5)) {
					_yOffset = yOffset * 1f/(float)Mathf.Abs(i-currJumping);
				}
				else 
					_yOffset = 0f;
			}
			fanPool[i].transform.position = new Vector3(fanOffsetX*(i+deletedObjects),
				getSinY(Mathf.Deg2Rad * ((i+deletedObjects)*30%360)) + _yOffset, 0f) + initOffset;
		}
	}

	void generateNextElement() {
		GameObject newObj = GameObject.Instantiate(fanVariations[getArandomNum()],
			new Vector3(fanOffsetX*currIndex, getSinY(Mathf.Deg2Rad * (currIndex*30%360)), 0f),
			Quaternion.identity) as GameObject;
		newObj.transform.position += initOffset;
		newObj.transform.SetParent(transform);
		fanPool.Add(newObj);
		currIndex++;
	}

	void generateFirstNElements(int n) {
		for(int i=0; i<n; i++) {
			generateNextElement();
		}
	}

	int getArandomNum() {
		int random = Random.Range(0, randomLimit);
		return random;
	}

	float getSinY(float angle) {
		return Mathf.Sin(angle) * amplitude;
	}

	IEnumerator up() {
		float time = 0f;
		jumping = true;
		while(time < .3f) {
			time += Time.deltaTime;
			if(jumping) {
				//Debug.Log(yOffset);
				yOffset += Mathf.Pow(time, .7f);
			}
			
			yield return null;
		}
		//jumping = false;
		//yOffset = 0f;
	}
}
