using OPSSDK;
using Ozeki.Media;
using Ozeki.Media.MediaHandlers;
using Ozeki.VoIP;

namespace OPSIVRSystem
{
    /// <summary>
    /// Manage the media data sources of a call.
    /// </summary>
    class MediaManager
    {

        /// <summary>
        /// Will be attached to calls.
        /// </summary>
        private IAudioReceiver phoneCallAudioReceiver;

        /// <summary>
        /// Will be attached to calls.
        /// </summary>
        private IAudioSender phoneCallAudioSender;

        /// <summary>
        /// Connects media handlers to each other
        /// </summary>
        private MediaConnector mediaConnector;

        /// <summary>
        /// Mixes audio from different sources. It will be connected to the PhoneCallListener.
        /// </summary>
        private AudioForwarder incomingAudioMixer;

        /// <summary>
        /// Mixes audio from different sources. It will be connected to the PhoneCallListener.
        /// </summary>
        private AudioForwarder outgoingAudioMixer;

        public MediaManager(ICall call)
        {
            mediaConnector = new MediaConnector();

            phoneCallAudioReceiver = new AudioForwarder();
            phoneCallAudioSender = new AudioForwarder();

            incomingAudioMixer = new AudioForwarder();
            outgoingAudioMixer = new AudioForwarder();
            
            call.ConnectAudioSender(outgoingAudioMixer);
            call.ConnectAudioReceiver(incomingAudioMixer);
            //mediaConnector.Connect(phoneCallAudioReceiver, incomingAudioMixer);
            //mediaConnector.Connect(outgoingAudioMixer, phoneCallAudioSender);

            //phoneCallAudioReceiver.AttachToCall(call);
            //phoneCallAudioSender.AttachToCall(call);

        }


        public void AttachAudioReceiverToCall(IAudioReceiver audioReceiver)
        {
            mediaConnector.Connect(incomingAudioMixer, audioReceiver);
        }

        public void AttachAudioSenderToCall(IAudioSender audioSender)
        {
            mediaConnector.Connect(audioSender, outgoingAudioMixer);
        }

        public void DetachAudioReceiverFromCall(IAudioReceiver receiver)
        {
            mediaConnector.Connect(incomingAudioMixer, receiver);
        }

        public void DetachAudioSenderFromCall(IAudioSender sender)
        {
            mediaConnector.Disconnect(sender, outgoingAudioMixer);
        }
    }
}
