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

public class ObjectsSpawnScript : MonoBehaviour {

	private Vector2[] spawns = new Vector2[]{new Vector2(-140f, -68f), new Vector2(-8f,-68f), new Vector2(124f,-68f), new Vector2(440f,-68f), new Vector2(572f,-68f)};
	private List<int> usedValues;
	private List<string> namesSpawned;
	public static List<string> toList;
	private int childrenIException;
	private Transform childrenTransform;

	void Awake (){
		namesSpawned = new List<string>();
		toList = new List<string> ();
		usedValues = new List<int>();

		initFunc ();
	}

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	public void initFunc(){
		usedValues.Add (0);
		usedValues.Add (1);

		for (int i = 0; i < 5; i++) {
			int childrenIndex = funcRandom (2,7,usedValues);

			if ((childrenIndex == 2 && usedValues.Contains (6)) || (childrenIndex == 6 && usedValues.Contains (2)) && (i > 3)){
				//usedValues.Add (childrenIndex);
				while(childrenIndex == 2 || childrenIndex == 6){
					childrenIndex = funcRandom (2,7,usedValues);
				}
			}

			if (i != 2) {
				positionObjects (i, childrenIndex);
				if (childrenIndex == 2 || childrenIndex == 6) {
					i++;
				}

			} else {
				while(childrenIndex == 2 || childrenIndex == 6){
					childrenIndex = funcRandom (2,7,usedValues);
				}
				positionObjects (i, childrenIndex);
			}

			usedValues.Add (childrenIndex);
			//Debug.Log (childrenIndex + ", i: "+i);
		}

		for(int i=0; i<7; i++){
			if (!usedValues.Contains (i))
				this.gameObject.transform.GetChild (i).gameObject.SetActive (false);
			else if(i<4){
				namesSpawned.Add(this.gameObject.transform.GetChild (i).gameObject.name);
			}
		}

		//for (int i = 0; i < namesSpawned.Count; i++)
		//	Debug.Log (namesSpawned[i]);
		List<int> itensException = new List<int> ();
		for (int i = 0; i < 3; i++) {
			int rIndex = Random.Range (0, namesSpawned.Count);
			while(itensException.Contains(rIndex)){
				rIndex = Random.Range (0, namesSpawned.Count);
			}
			//Debug.Log (i+" : "+rIndex);
			itensException.Add (rIndex);
			toList.Add(namesSpawned[rIndex]);
		}
		//for (int i = 0; i < toList.Count; i++) {
		//	Debug.Log (toList [i]);
		//}
	}

	int funcRandom(int init, int fim, List<int> valuesException){
		int randomIndex = Random.Range (init, fim);
		while(valuesException.Contains(randomIndex)){
			randomIndex = Random.Range (init, fim);
		}
		return randomIndex;
	}

	void positionObjects(int i, int childrenIndex){
		childrenTransform = this.gameObject.transform.GetChild (childrenIndex);
		if (childrenIndex == 2) {
			Vector2 varTemp = new Vector2 (spawns[i].x + 15f, 0f);
			childrenTransform.localPosition = varTemp;
		}
		else if(childrenIndex == 6){
			Vector2 varTemp = new Vector2 (spawns[i].x + 75f, spawns[i].y);
			childrenTransform.localPosition = varTemp;
		}
		else
			childrenTransform.localPosition = spawns[i];
	}
}
