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

public enum NetworkMode
{
    Local,          // Execute only on the player who clicked
    NetworkAll,     // Execute on all players
    NetworkOwner    // Execute only on the owner/master
}

public class VRCButton : UdonSharpBehaviour
{


    [Header("Target Settings")]
    public UdonSharpBehaviour targetScript;
    public string eventName;

    [Header("Network Settings")]
    public NetworkMode networkMode = NetworkMode.NetworkAll;

    [Header("Sound Settings")]
    public AudioPoolPlayer audio;
    public bool playSoundForEveryone = false;


    void Start()
    {
        // Validate setup on start
        if (targetScript == null)
        {
            Debug.LogWarning($"[VRCButton] No target script assigned on {gameObject.name}");
        }
        else if (string.IsNullOrEmpty(eventName))
        {
            Debug.LogWarning($"[VRCButton] No event name set on {gameObject.name}");
        }
    }

    public override void Interact()
    {
        if (targetScript == null)
        {
            Debug.LogError("[VRCButton] Cannot interact: targetScript is null");
            return;
        }

        if (string.IsNullOrEmpty(eventName))
        {
            Debug.LogError("[VRCButton] Cannot interact: eventName is null or empty");
            return;
        }

        // Send the event based on network mode
        switch (networkMode)
        {
            case NetworkMode.Local:
                targetScript.SendCustomEvent(eventName);
                break;
            case NetworkMode.NetworkAll:
                targetScript.SendCustomNetworkEvent(VRC.Udon.Common.Interfaces.NetworkEventTarget.All, eventName);
                break;
            case NetworkMode.NetworkOwner:
                targetScript.SendCustomNetworkEvent(VRC.Udon.Common.Interfaces.NetworkEventTarget.Owner, eventName);
                break;
        }

        // New sound playback logic
        if (audio != null)
        {
            if (playSoundForEveryone)
            {
                audio.SendCustomNetworkEvent(VRC.Udon.Common.Interfaces.NetworkEventTarget.All, nameof(audio.Play));
            }
            else
            {
                audio.Play();
            }
        }

    }
}
