using System.Collections;
using System.Collections.Generic;
using System.Linq;

using UnityEngine;

public class EnvironmentManager : MonoBehaviour
{
	public Transform CloudsContainer;
	private List<Transform> _clouds;
	private List<int> _cloudIndexes;
	private float _lastSortedTime;
	
	public Transform UpCar;
	private List<Transform> _upCarClones;
	public Transform DownCar;
	private List<Transform> _downCarClones;
	public Color[] CarColors;

	private float _lastCarTime;

	// Use this for initialization
	void Start ()
	{
		_upCarClones = new List<Transform>();
		_downCarClones = new List<Transform>();
		_clouds = new List<Transform>();
		for (var i = 0; i < CloudsContainer.childCount; i++)
		{
			_clouds.Add(CloudsContainer.GetChild(i));
		}
	}
	
	// Update is called once per frame
	void Update ()
	{
		if (_lastCarTime > 1)
		{
			if (Random.Range(0, 5) >= 2)
			{
				var isUpCar = Random.Range(0, 2) == 1;

				var car = Instantiate(isUpCar ? UpCar : DownCar);
				car.position = isUpCar ? UpCar.position : DownCar.position;

				var colorIndex = Random.Range(0, CarColors.Length);
				car.GetComponent<SpriteRenderer>().color = CarColors[colorIndex];

				if (isUpCar)
				{
					_upCarClones.Add(car);
				}
				else
				{
					_downCarClones.Add(car);
				}
			}
			
			_lastCarTime = 0;
		}

		_lastCarTime += Time.deltaTime;
		
		if (_lastSortedTime >= 60 || _cloudIndexes == null)
		{
			_cloudIndexes = RandomRangeList(0, _clouds.Count);
			_lastSortedTime = 0;
		}

		var upCarsToDestroy = new List<Transform>();
		var downCarsToDestroy = new List<Transform>();

		foreach (var car in _upCarClones)
		{
			car.Translate(Vector3.right * Time.deltaTime * 8);
			
			if (car.position.x > DownCar.position.x)
			{
				upCarsToDestroy.Add(car);
			}
		}
		
		foreach (var car in _downCarClones)
		{
			car.Translate(Vector3.left * Time.deltaTime * 8);

			if (car.position.x < UpCar.position.x)
			{
				downCarsToDestroy.Add(car);
			}
		}
		
		foreach (var car in upCarsToDestroy)
		{
			_upCarClones.Remove(car);
			Destroy(car.gameObject);
		}
		
		foreach (var car in downCarsToDestroy)
		{
			_downCarClones.Remove(car);
			Destroy(car.gameObject);
		}
		
		
		foreach (var i in _cloudIndexes)
		{
			_clouds[i].transform.Translate(Vector3.left * Time.deltaTime * ((i+1) / 32f));

			if (_clouds[i].transform.position.x < -15)
			{
				var pos = _clouds[i].transform.position;
				pos.x = 40;
				_clouds[i].transform.position = pos;
			}
		}
		
		_lastSortedTime += Time.deltaTime;
	}
	
	public List<int> RandomRangeList(int start, int count)
	{
		var randomList = new List<int>();
		var remaining = Enumerable.Range(start, count).ToList();
 
		while(remaining.Count > 0)
		{
			var randomIndex = Random.Range(0, remaining.Count);
			randomList.Add(remaining[randomIndex]);
			remaining.RemoveAt(randomIndex);
		}
		return randomList;
	}
}
