using System;
using Ozeki.VoIP;

namespace _09_PredictiveDialer
{
    internal class Softphone
    {
        ISoftPhone _softphone;
        IPhoneLine _phoneLine;

        public Softphone()
        {
            _softphone = SoftPhoneFactory.CreateSoftPhone(5000, 10000);
        }

        public void Register(bool registrationRequired, string displayName, string userName, string authenticationId, string registerPassword, string domainHost, int domainPort)
        {
            try
            {
                var account = new SIPAccount(registrationRequired, displayName, userName, authenticationId, registerPassword, domainHost, domainPort);

                _phoneLine = _softphone.CreatePhoneLine(account);

                _phoneLine.RegistrationStateChanged +=_phoneLine_RegistrationStateChanged;

                _softphone.RegisterPhoneLine(_phoneLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error during SIP registration: {0}", ex.ToString());
            }
        }

        public void Unregister()
        {
            _softphone.UnregisterPhoneLine(_phoneLine);
        }

        void _phoneLine_RegistrationStateChanged(object sender, RegistrationStateChangedArgs e)
        {
            var handler = PhoneLineStateChanged;
            if (handler != null)
                handler(this, e);
        }

        public IPhoneCall CreateCall(string member)
        {
            return _softphone.CreateCallObject(_phoneLine, member);
        }

        public event EventHandler<RegistrationStateChangedArgs> PhoneLineStateChanged;
    }
}
