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

public class LevelRepeater : MonoBehaviour
{
    public Transform player = null;
    public float distanceInfront = 300.0f;
    public float distanceBehind = 50.0f;
    public List<GameObject> levelSections = new List<GameObject>();
    public MaterialRepeaterThing materialRepeaterThing;

    private List<GameObject> m_activeLevelSections = new List<GameObject>();
    private Vector3 m_lastSectionEndPosition = new Vector3();

    void Start()
    {
        Reset();
    }

    public void Reset()
    {
        foreach (GameObject levelSec in m_activeLevelSections)
            Destroy(levelSec);

        m_activeLevelSections.Clear();
        GameObject newSection = (GameObject)Instantiate(levelSections[Random.Range(0, levelSections.Count)]);
        newSection.transform.position = transform.position + (Vector3.right * newSection.collider.bounds.extents.x);
        m_lastSectionEndPosition = transform.position + (Vector3.right * newSection.collider.bounds.size.x);
        m_activeLevelSections.Add(newSection);
        Debug.Log("Creating initial section: " + newSection.name);
    }

    void Update()
    {
        while(player.position.x + distanceInfront > m_lastSectionEndPosition.x)
        {
            GameObject newSection = (GameObject)Instantiate(levelSections[Random.Range(0, levelSections.Count)]);
            newSection.transform.position = m_lastSectionEndPosition + (Vector3.right * newSection.collider.bounds.extents.x);
            m_lastSectionEndPosition.x += newSection.collider.bounds.size.x;
            m_activeLevelSections.Add(newSection);
            materialRepeaterThing.ManualUpdate();
            Debug.Log("Creating section: " + newSection.name);
        }

        for (int i = m_activeLevelSections.Count - 1; i >= 0; i--)
        {
            GameObject levelSec = m_activeLevelSections[i];
            if (player.position.x - distanceBehind > levelSec.transform.position.x + levelSec.collider.bounds.extents.x)
            {
                Debug.Log("Deleting section: " + levelSec.name);
                Destroy(levelSec);
                m_activeLevelSections.Remove(levelSec);
            }
        }
    }

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.cyan;
        Gizmos.DrawLine(player.position, player.position + (Vector3.right * distanceInfront));
        Gizmos.color = Color.magenta;
        Gizmos.DrawLine(player.position, player.position - (Vector3.right * distanceBehind));
    }
}