using UnityEngine;
using System.Collections;


public class SectionManager2 : MonoBehaviour
{
		public Section[]  sections ;
		
		public static SectionManager2 inst;
		//public float zDistance;
		//public float yPos;
		
		
		Section currentSection;
		Section lastSection;
		Vector3 newSectionPos;
		
		MainCharacter player;
		float newTarget;
		
		void Awake ()
		{		
				inst = this;
				//zDistance = this.transform.position.z;
		}
		
		void Start ()
		{
				player = MainCharacter.inst;
				AddSection ();
		}
		
		public void Restart ()
		{
				foreach (Section section in this.GetComponentsInChildren<Section>()) {
						Destroy (section.gameObject);
				}
				lastSection = null;
				currentSection = null;
				newTarget = 0;
				AddSection ();
		}
		void Update ()
		{
				if (player.transform.localPosition.x > newTarget) {
						AddSection ();
				}
		}
		
		void AddSection ()
		{
				if (currentSection != null)
						newTarget += GetWidth (currentSection);
				Section section = Instantiate (GetRandomSection ()) as Section;
				section.transform.parent = this.transform;
				section.transform.localPosition = new Vector3 (newTarget, 0, 0);
				if (lastSection != null) 
						Destroy (lastSection.gameObject);
				lastSection = currentSection;
				currentSection = section;
		}
		
		float GetWidth (Section section)
		{
				/*if (section.GetComponentInChildren <Collider> () == null) {
						return 10;
				}*/
				Bounds totalBounds = section.GetComponentInChildren <SpriteRenderer> ().bounds;
				SpriteRenderer[] colliders = section.GetComponentsInChildren <SpriteRenderer> ();
		
				foreach (SpriteRenderer col in colliders) {
						totalBounds.Encapsulate (col.bounds);
				}
				return totalBounds.size.x;
		}
	
		Section GetRandomSection ()
		{
				int nSection = Random.Range (0, sections.Length);
				return sections [nSection];
		}
}
