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

public class TrackManager : MonoBehaviour
	{
	public TrackGenerator trackGenerator;
    public GameControler gameController;
    //public WidgetManager widgetManager;
	public delegate void fReceiveEvent(Event e);
    private float timer = 0;
    private float errorTimer = 0;
	public float timeBetweenTracks = 10.0f;
    public float timeBetweenErrors = 25.0f;
    public int currentCognitiveLoad = 0;
	public int maxCognitiveLoad = 2;
    public int maxTracks = 1;
    public int maxErrors = 5;

	// ========== Variables ======================

	List<Track> activeTracks = new List<Track>();
    List<Track> activeErrorTracks = new List<Track>();
    int targetTracks = 1;

	// =========== Functions =====================

	void Start ()
	{
        Debug.Log("TrackManager.Start()");
		gameObject.AddComponent<TrackGenerator>();
        trackGenerator = GetComponent<TrackGenerator>();
        //timer = 0;        
	}

	public int getNumberOfActiveTracks()
	{
		return activeTracks.Count;
	}

    public int getNumberOfErrorTracks()
    {
        return activeErrorTracks.Count;
    }

	public void restart()
	{
		Debug.Log ("Restart");
		Start ();
	}



	void Update ()
	{
		if (gameController.gameEnded)
		{
			return;
		}

        this.maxCognitiveLoad = gameController.currentLevel * gameController.cogLoadPerLevel;
        //Debug.Log("maxCognitiveLoad is " + maxCognitiveLoad);
        this.maxTracks = gameController.currentLevel * gameController.trackIncreasePerLevel;
        //Debug.Log("maxTracks is " + maxTracks);

        // regular tracks
        timer += Time.deltaTime;
        //Debug.Log("timer is " + timer);  
        // error tracks
        errorTimer += Time.deltaTime;
        //Debug.Log("error timer is " + errorTimer);
        /*
        if (errorTimer > timeBetweenErrors)
        {
            //Debug.Log("should I make an error?");
            if (activeErrorTracks.Count < maxErrors)
            {
                Debug.Log("making error track");
                //Debug.Log("TrackManager.Update() - creating a new track");
                // Start a new track
                Track t = trackGenerator.generateNewTrack(1, true);
                if (t != null)
                {
                    activeErrorTracks.Add(t);
                    this.currentCognitiveLoad += t.cognitiveLoad;
                    //Debug.Log("Adding " + t.cognitiveLoad + " to Cognitive Load");
                }
            }
            else ///we're full? Let's see what these tracks are...
            {
                //foreach (Track t in activeErrorTracks)
                //  Debug.Log(t.getInstruction());
            }
            errorTimer = 0;
        }        
        else
            */
            
            if (timer > timeBetweenTracks){
              
			if (activeTracks.Count < this.maxTracks && this.currentCognitiveLoad < this.maxCognitiveLoad )
            {
                Debug.Log("making track");
                //Debug.Log("TrackManager.Update() - creating a new track");
                // Start a new track
                Track t = trackGenerator.generateNewTrack(this.maxCognitiveLoad-this.currentCognitiveLoad, false);
                if (t != null)
                {
                    if (t.isErrorEvent)
                        activeErrorTracks.Add(t);
                    else
                        activeTracks.Add(t);
                    this.currentCognitiveLoad += t.cognitiveLoad;
                    //Debug.Log("Adding " + t.cognitiveLoad + " to Cognitive Load");
                }
            }
            else ///we're full? Let's see what these tracks are...
            {
                //foreach (Track t in activeTracks)
                  //  Debug.Log(t.getInstruction());
            }
            timer = 0;
        }

        
        

        // clear cleared tracks
        foreach (Track t in activeTracks)
        {
            t.update();
            if (t.finished)
            {
                this.currentCognitiveLoad -= t.cognitiveLoad;
                //Debug.Log("Subtracting " + t.cognitiveLoad + " from Cognitive Load");
            }
        }
        activeTracks.RemoveAll(item => item.finished == true);
       
        foreach (Track t in activeErrorTracks)
        {
            t.update();
            if (t.finished)
            {                
                this.currentCognitiveLoad -= t.cognitiveLoad;
                //Debug.Log("Subtracting " + t.cognitiveLoad + " from Cognitive Load");
            }
        }
        activeErrorTracks.RemoveAll(item => item.finished == true);

    }


    void finish()
    {
        foreach (Track t in activeTracks)
        {
            t.finish();
        }
        activeTracks.Clear();
    }

}

