using UnityEngine;
using System.Collections;
using Janus;
using Jeli;
using System.Collections.Generic;

public class CubeScript : MonoBehaviour {

	public GameObject cube;                   // holds a cube game object
	public Timeline<string> cubeCommand;      // string timeline used for sending commands between clients
	int cubeNumber = 0;                       // unique identifier for each cube created by this client              
//	List<GameObject> cubes = new List<GameObject>();
	
	void Start () {
		Debug.Log("Starting Cube Script");
		// create a timeline 
		cubeCommand = TimelineManager.Default.Get<string>("command");
		// listen for commands being inserted on both  local and remote clients
		cubeCommand.EntryInserted += HandleCubeCommandEntryInserted;
	}

    // Event handler for entries inserted into the cubeCommand timeline
	void HandleCubeCommandEntryInserted (Timeline<string> timeline, TimelineEntry<string> entry)
	{
		// the various parts of the command are separated by commas
		string[]tokens = entry.Value.Split(',');
		string action = tokens[0];
		
		// this is a command to create a new cube
		if (action == "create")
		{
		    uint cubeNumber = uint.Parse(tokens[1]);
			// get the client id number of the client who initiated this command
			ushort cubeCreator = ushort.Parse(tokens[2]);
			
			// determine where the cube should be placed based on the mouse position
			var mousePos = Input.mousePosition;
			Vector3 cubePos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, -Camera.main.transform.position.z));
			
			// create a new cube
			GameObject instance = Instantiate(cube, cubePos, Quaternion.identity) as GameObject;
			instance.GetComponent<CubeController>().Create(cubeNumber, cubeCreator);
			
		}
		else if (action == "delete")
		{
			string stringId = tokens[1];
			GameObject instance = GameObject.Find(stringId);
			Destroy(instance);
		
		}
	}
	
		
	void Update () {

		// create a new cube when the C key is pressed
		if (Input.GetKeyDown(KeyCode.C))
		{		
			// the command timeline is a string, a create command is composed of three parts separated by commas
			// 1) the word "create"
			// 2) an integer the is a unique number for a cube created by this client
			// 3) the index number of this client
			cubeCommand[0] = "create," + cubeNumber + "," + Janus.TimelineClient.Index;
			cubeNumber++;
		}
	}
}
