using UnityEngine;
using System.Collections;
using UnityEngine.UI;


[RequireComponent(typeof(AudioSource))]
public class StepSequencer2 : Photon.MonoBehaviour {
	public UnityEngine.UI.Toggle toggleMode1;
	public UnityEngine.UI.Toggle toggleMode2;
	public float bpm = 120f;
	public int numBeatsPerSegment = 1;
	public bool sendMode;
	public int flip ;
	public double nextEventTime;
	private bool running = false;
	public float bpmSlider = 120f;

	void Start() {

		nextEventTime = AudioSettings.dspTime;
		running = true;
		toggleMode1 = GameObject.Find ("ToggleMode1").GetComponent<UnityEngine.UI.Toggle>();
		toggleMode2 = GameObject.Find ("ToggleMode2").GetComponent<UnityEngine.UI.Toggle>();
	}
	void FixedUpdate() {
		if (!running)
			return;
		SliderChange ();
		double time = AudioSettings.dspTime;

		if (time > nextEventTime) {
			if (flip != 0) {flip ++;}
			if (flip >= 17) {flip = 1;}
			flipTheCube();
		}

		}

	void flipTheCube() {
				//localFlip = flip;

		//if (photonView.isMine == true) {
			//SyncFlips (flip);
		//	audioSources [flip].clip = clips [flip];
		//	audioSources [flip].PlayScheduled (nextEventTime);
			//			Debug.Log("Scheduled source " + flip + " to start at time " + nextEventTime);
			nextEventTime += 60.0F / bpm * numBeatsPerSegment;
			//Debug.Log (flip);
			//flip = flip + 1;
		//}
	}
	void SliderChange() {
//		float bpmSlider = GameObject.Find("BPMSlider").GetComponent<BPMSlider>().bpmSlider.value;
		//bpm = bpmSlider;//
		bpm = 120.0F;
		//Debug.Log (bpm);
	}
	void OnJoinedRoom()
	{
		nextEventTime = AudioSettings.dspTime;
		flip = 17;


	}
	void OnPhotonPlayerConnected() {
		SyncFlips (flip, toggleMode1.isOn, toggleMode2.isOn);
	}

	[RPC] void SyncFlips(int currentFlip, bool mode1, bool mode2) //Server forcing all clients to syncronyze flips
	{
		GameObject.Find("ToggleMode1").GetComponent<Toggle>().isOn = mode1;
		GameObject.Find("ToggleMode2").GetComponent<Toggle>().isOn = mode2;
		GameObject.Find("StepSequencer2").GetComponent<StepSequencer2>().flip = currentFlip;
		//Debug.Log (currentFlip);
		if (photonView.isMine == true) {
			photonView.RPC ("SyncFlips", PhotonTargets.Others, currentFlip, mode1, mode2);
		} 
		
	}

}
