using System;
using Ozeki.Media;
using Ozeki.VoIP;

namespace _10_MultiSIPAccount
{
    class CallHandler
    {
        Softphone _softphone;
        CallInfo _callInfo;
        MediaConnector _connector;
        PhoneCallAudioSender _mediaSender;


        public CallHandler(Softphone softphone, CallInfo callInfo)
        {
            _softphone = softphone;
            _callInfo = callInfo;
            _mediaSender = new PhoneCallAudioSender();
            _connector = new MediaConnector();
        }

        public void Start(IPhoneLine phoneLine)
        {
            var call = _softphone.CreateCall(phoneLine, _callInfo.PhoneNumber);
            call.CallStateChanged += OutgoingCallStateChanged;
            _mediaSender.AttachToCall(call);
            call.Start();
            Console.WriteLine("Trying to call: {0} with {1}.", _callInfo.PhoneNumber, phoneLine.SIPAccount.UserName);
        }

        /// <summary>
        /// Occurs, when the call has been ended.
        /// </summary>
        public event EventHandler Completed;

        void TextToSpeech(string text)
        {
            var textToSpeech = new TextToSpeech();
            _connector.Connect(textToSpeech, _mediaSender);
            textToSpeech.AddAndStartText(text);
        }

        void OutgoingCallStateChanged(object sender, CallStateChangedArgs e)
        {
            if (e.State == CallState.Answered)
            {
                Console.WriteLine("\nCall has been accepted by {0}.", _callInfo.PhoneNumber);
                TextToSpeech(_callInfo.Message);
                Console.WriteLine("Playing message: \n\"{0}\"", _callInfo.Message);
            }
            else if (e.State.IsCallEnded())
            {
                Console.WriteLine("\nCall has been ended: {0}.", _callInfo.PhoneNumber);

                _softphone.AddAvailablePhoneLine(((IPhoneCall)sender).PhoneLine);

                var handler = Completed;
                if (handler != null)
                    handler(this, EventArgs.Empty);
            }
        }
    }
}
