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

public class SFXPlayer : UdonSharpBehaviour
{
    [Header("Audio Settings")]
    public AudioPoolPlayer audio;
    public bool playSoundForEveryone = false;

    [Header("Particle Settings")]
    public ParticleSystem particles;
    public NetworkMode particleNetworkMode = NetworkMode.Local;

    public void Play()
    {
        if (particles != null) Dispatch(particleNetworkMode, nameof(PlayParticles));

        if (audio != null)
        {
            audio.Play();
            if (playSoundForEveryone)
                audio.SendCustomNetworkEvent(VRC.Udon.Common.Interfaces.NetworkEventTarget.Others, nameof(audio.Play));
        }
    }

    private void Dispatch(NetworkMode mode, string eventName)
    {
        if (mode == NetworkMode.NetworkOwner)
        {
            if (Networking.IsOwner(gameObject)) SendCustomEvent(eventName);
            return;
        }
        SendCustomEvent(eventName);
        if (mode == NetworkMode.NetworkAll)
            SendCustomNetworkEvent(VRC.Udon.Common.Interfaces.NetworkEventTarget.Others, eventName);
    }

    public void PlayParticles()
    {
        if (particles != null)
        {
            particles.Stop();
            particles.Play();
        }
    }
}
