using UnityEngine;
using System.Collections;

public class Nivel : MonoBehaviour {

    public static Nivel current;

    private ObjetoColor[] objetosColor;
    public Checkpoint[] checkpoints;
    public Transform protagonista;
    public AudioSource audioSourcePrefab;

	void Awake()
    {
        current = this;
        objetosColor = GetComponentsInChildren<ObjetoColor>();
        checkpoints = GetComponentsInChildren<Checkpoint>();
    }

    void Start()
    {
        for (int i = 0; i < checkpoints.Length; i++)
            checkpoints[i].entered = i <= Checkpoint.lastCheckboxIndex;

        if (Checkpoint.last != null)
        {
            protagonista.transform.position = Checkpoint.last.transform.position;
            if (Checkpoint.last.direccion == Direccion.izquierda)
                protagonista.GetComponent<UnityStandardAssets._2D.PlatformerCharacter2D>().Move(-.1f, false, false);
        }

        ActualizarColor();
    }

    public void ActualizarColor()
    {
        var particulas = protagonista.GetComponentInChildren<ParticleSystem>();
        particulas.enableEmission = Cromometro.current.currentColor != WaveColor.black;
        if(particulas.emission.enabled)
            particulas.startColor = ControlColor.GetColor(Cromometro.current.currentColor);
        foreach (var o in objetosColor)
            o.ActualizarColor();
    }

    public void ContactoConCheckpoint(Checkpoint c)
    {
        Nivel.PlayAudio(c.audioClip, c.transform.position);

        for (int i = 0; i < checkpoints.Length; i++)
            if(checkpoints[i] == c)
            {
                Checkpoint.lastCheckboxIndex = Mathf.Max(i, Checkpoint.lastCheckboxIndex);
                return;
            }
    }

    public static void PlayAudio(AudioClip clip)
    {
        PlayAudio(clip, Camera.main.transform.position);
    }
    public static void PlayAudio(AudioClip clip, Vector3 pos)
    {
        var source = Instantiate(current.audioSourcePrefab).GetComponent<AudioSource>();
        source.clip = clip;
        source.transform.position = pos;
        source.Play();
    }
}
