﻿using HutongGames.PlayMaker;

namespace Dissonance.Integrations.PlayMaker
{
    [ActionCategory("Dissonance Voice Comms")]
    [Tooltip("Starts transmitting the player's microphone input to all players in the given chat room.")]
    public class TransmitToChatRoom
        : FsmStateAction
    {
        [Tooltip("The name of the chat room to transmit to.")]
        [RequiredField]
        public FsmString roomName;

        [Tooltip("Use the local player's position to transmit with 3D positional audio.")]
        public FsmBool positional;

        [Tooltip("Priority to send the voice with, higher priority voices drown out lower priority voices")]
        [ObjectType(typeof(ChannelPriority))]
        public FsmEnum priority;

        private DissonanceComms _comms;
        private RoomChannel? _channel;

        public override void Awake()
        {
            base.Awake();

            _comms = GetVoiceComms();

            if (ReferenceEquals(_comms, null))
                LogError("Cannot find a DissonanceVoiceComms component in the scene.");
        }

        public override void Reset()
        {
            roomName.Value = null;
            positional.Value = false;
            priority.Value = ChannelPriority.None;
        }

        public override void OnEnter()
        {
            if (roomName.IsNone || roomName.Value == null)
            {
                LogWarning("Room name not set.");
                return;
            }

            var comms = GetVoiceComms();
            if (comms != null)
                _channel = comms.RoomChannels.Open(roomName.Value, positional.Value, (ChannelPriority)priority.Value);
        }

        public override void OnExit()
        {
            var comms = GetVoiceComms();
            if (comms != null && _channel != null)
            {
                comms.RoomChannels.Close(_channel.Value);
                _channel = null;
            }
        }

        public override void OnUpdate()
        {
            if (_channel != null)
            {
                var channel = _channel.Value;
                channel.Positional = positional.Value;
                channel.Priority = (ChannelPriority)priority.Value;
            }
        }

        private DissonanceComms GetVoiceComms()
        {
            if (_comms == null)
                _comms = UnityEngine.Object.FindObjectOfType<DissonanceComms>();

            return _comms;
        }
    }
}
