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

public class SphereController : MonoBehaviour {
	private CsoundUnity csoundUnity;
	private Vector3 initialSize;
	private Vector3 finalSize;
	float progress = 0;
	private string channelName;


	void Awake() 
	{
		csoundUnity =  GameObject.FindObjectOfType(typeof(CsoundUnity)) as CsoundUnity;
	}	 
	
	void Start () 
	{
		initialSize = new Vector3(2, 2, 2);
		finalSize = new Vector3(.01f, .01f, .01f);
		//find number of instances, use it to set index, set name for diagnostic purposes..
		int index = GameObject.FindGameObjectsWithTag ("Sphere").Length;
		gameObject.name = "Sphere"+index;

		//create unique channel name based on inxex
		channelName = "freq"+index;

		//create new object
		Invoke("createNewSphere", Random.Range(0.1f, 1f));

		//create instance of Csound instrument, passing the index as p5. Initial freq is passed to p4
		if(csoundUnity)
			csoundUnity.sendScoreEvent("i\"SPHERE\" 0 10 " + Random.Range(100, 1000) + " " + index);


	}
	
	// Update is called once per frame
	void Update () 
	{
		transform.localScale = Vector3.Lerp(initialSize, finalSize, progress);
        progress += Time.deltaTime;
		//modify frequency as the object gets smaller....
	 	csoundUnity.setChannel(channelName, transform.localScale.x/2f);
	}

	void createNewSphere()
	{
		GameObject clone = Instantiate (gameObject) as GameObject;
		clone.transform.position = new Vector3(Random.Range(-5, 5), Random.Range(-5, 5), Random.Range(-5, 5));
	}
}
