
using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;

public enum MusicEventType
{
	INTERNAL = -1,
	None,
	WhereInTheWorld,
	RockapellaIdent
}

public enum SFXEventType
{
	INTERNAL = -1,
	None,
	Buzzer
}

[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
public class GameManager : UdonSharpBehaviour
{
	[Header("Player Data")]
	public PlayerPodium[] PlayerPodiums;

	[Header("Audio")]
	public AudioClip BuzzerSound = null;

	public AudioClip WhereInTheWorld = null;
	public AudioClip RockapellaIdent = null;

	public AudioSource MusicPlayer = null;
	[UdonSynced, FieldChangeCallback(nameof(MusicEvent))] private MusicEventType _MusicEvent = MusicEventType.None;

	public AudioSource SFXPlayer = null;
	[UdonSynced, FieldChangeCallback(nameof(SFXEvent))] private SFXEventType _SFXEvent = SFXEventType.None;

	[UdonSynced] private bool BuzzInAllowed = true;
	[UdonSynced] private int _BuzzedInPlayer = 0;


	public void PlayerBuzzedIn(int PlayerNumber)
	{
		if (!BuzzInAllowed) { return; }

		BuzzInAllowed = false;
		_BuzzedInPlayer = PlayerNumber;
		SFXEvent = SFXEventType.Buzzer;
		RequestSerialization();

		PlayerPodiums[PlayerNumber - 1].IncreaseScoreBy10();
		PlayerPodiums[PlayerNumber - 1].RequestSerialization();
	}
	public void CancelBuzzIn() {
		BuzzInAllowed = true;
		_BuzzedInPlayer = 0;
		RequestSerialization();
	}


	public void StartGame()
	{
		for (int i = 0; i < PlayerPodiums.Length; i++)
		{
			Networking.SetOwner(Networking.InstanceOwner, PlayerPodiums[i].gameObject);

		}

		PlayerPodiums[0].IncreaseScoreBy10();
		PlayerPodiums[0].RequestSerialization();

		PlayerPodiums[1].IncreaseScoreBy5();
		PlayerPodiums[1].RequestSerialization();

		PlayerPodiums[2].DecreaseScoreBy5();
		PlayerPodiums[2].RequestSerialization();
	}


	public void PlayWhereInTheWorld()
	{
		MusicEvent = MusicEventType.WhereInTheWorld;
	}

	public void PlayRockapellaIdent()
	{
		MusicEvent = MusicEventType.RockapellaIdent;
	}


	public MusicEventType MusicEvent
	{
		set
		{
			_MusicEvent = value;

			MusicPlayer.Stop();

			switch(_MusicEvent)
			{
				case MusicEventType.WhereInTheWorld:	MusicPlayer.clip = WhereInTheWorld;	break;
				case MusicEventType.RockapellaIdent:	MusicPlayer.clip = RockapellaIdent;	break;
				default: break;
			}

			if (_MusicEvent != MusicEventType.None)
				MusicPlayer.Play();

			RequestSerialization();
		}
		get => _MusicEvent;
	}

	public SFXEventType SFXEvent
	{
		set
		{
			_SFXEvent = value;

			SFXPlayer.Stop();

			switch (_SFXEvent)
			{
				case SFXEventType.Buzzer: SFXPlayer.clip = BuzzerSound; break;
				default: break;
			}

			if (_SFXEvent != SFXEventType.None)
				SFXPlayer.Play();

			RequestSerialization();
		}
		get => _SFXEvent;
	}
}
