using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Renderer))]
//[RequireComponent(typeof(AudioSource))]

public class Spectrum : MonoBehaviour {

	/*public GameObject prefab;
	public float line = 5f;
	public float spacing = 2f;
    public GameObject[] squares;*/
    public AudioSource audio;
    

    public int width = 500;
    public int height = 100;
    public Color backgroundColor = Color.black;
    public Color waveformColor = Color.green;
    public int size = 2048;

    Color[] blank;
    Texture2D texture;
    float[] samples;


    IEnumerator UpdateWaveForm()
    {
        while (true)
        {
            GetCurWave();
            yield return new WaitForSeconds(0.1f);
        }
    }

	void Start()
	{
        
        /*for (int x = 0; x < line; x++)
		{
			Vector3 pos = new Vector3(x, 0, 0) * spacing;
			Instantiate(prefab, pos, Quaternion.identity);
		}
        squares = GameObject.FindGameObjectsWithTag("Line");*/
        samples = new float[size];

        // create the texture and assign to the guiTexture:
        texture = new Texture2D(width, height);
        GetComponent<SpriteRenderer>().material.mainTexture = texture;
        print(GetComponent<SpriteRenderer>().material.mainTexture = texture);
        Debug.Log(texture);
        
        // create a 'blank screen' image
        blank = new Color[width * height];

        for (var i = 0; i < blank.Length; i++)
        {
            blank[i] = backgroundColor;
        }

        // refresh the display each 100mS
        StartCoroutine(UpdateWaveForm());
	}

    void GetCurWave()
    {
        // clear the texture
        texture.SetPixels(blank, 0);

        // get samples from channel 0 (left)
        audio.GetOutputData(samples, 0);

        // draw the waveform
        for (var i = 0; i < size; i++)
        {
            texture.SetPixel((int)((width * i) / size), (int)(height * (samples[i] + 1f) / 2), waveformColor);
        }
        // upload to the graphics card
        texture.Apply();
    }

	// Update is called once per frame
	void Update () 
    {
        /*float[] spectrum = AudioListener.GetSpectrumData(1024, 0, FFTWindow.Hamming);
        for(int i =0; i<line;++i)
        {
            Vector2 previousScale = squares[i].transform.localScale;
            previousScale.y = spectrum[i] * 20;
            squares[i].transform.localScale = previousScale;
        }*/
	}
}
