using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Ozeki.VoIP;

namespace _10_MultiSIPAccount
{
    class Program
    {
        static Softphone _mySoftphone;
        static string _path;
        static CallInfo _callInfo;
        static List<CallInfo> _callList;
        static int _maxConcurrentCall;
        static Autodialer _autodialer;

        static void Main()
        {
            InitSoftphone();
            ShowGreetingMessage();
            _mySoftphone.ReadRegisterInfos();

            BlockExit();
        }

        static void InitSoftphone()
        {
            _mySoftphone = new Softphone();
            _mySoftphone.PhoneLineStateChanged += mySoftphone_PhoneLineStateChanged;
            _path = @"../../Resources/ExampleCSV.csv";
            _callList = new List<CallInfo>();
        }


        static void mySoftphone_PhoneLineStateChanged(object sender, RegistrationStateChangedArgs e)
        {
            Console.WriteLine("Phone line state changed: {0}", e.State);

            if (e.State == RegState.Error || e.State == RegState.NotRegistered)
            {
                Console.WriteLine("\nSIP Account was not valid, please set a new one:");
                _mySoftphone.ReadRegisterInfos();
            }

            if (e.State == RegState.RegistrationSucceeded)
            {
                Console.WriteLine("Registration succeeded - Online!\n");

                GetNewAccount();
            }
        }

        static void GetNewAccount()
        {
            Console.WriteLine("To add new SIP Account, press Y");

            string newAccount = Console.ReadKey(true).Key.ToString();
            if (newAccount.ToUpper() == "Y")
            {
                _mySoftphone.ReadRegisterInfos();
            }
            else
            {
                Console.WriteLine("The softphone is ready to be used with {0} accounts:",
                                  _mySoftphone.GetSipAccountCount());
                _mySoftphone.ListSipAccounts();
                GetMaxConcurrentCall();
                GetCSV();
            }
        }

        static void GetMaxConcurrentCall()
        {
            while (_maxConcurrentCall == 0)
            {
                try
                {
                    Console.Write("Please enter how many calls can be made simultaneously: ");
                    _maxConcurrentCall = Int32.Parse(Console.ReadLine());
                }
                catch
                {
                    Console.WriteLine("Wrong input. Please enter an integer number.");
                }
            }
        }

        static void GetCSV()
        {
            Console.Write("Please enter a path to a .csv file (f.e.: C:\\ExampleCSV.csv) or press Enter to load deafult file: ");
            string getPath = Console.ReadLine();

            if (!String.IsNullOrEmpty(getPath))
            {
                _path = getPath;
            }

            var fileI = new FileInfo(_path);
            Console.WriteLine("\nThe file's path is: {0}.\n", fileI.FullName);

            ReadCSV();
        }

        static void ReadCSV()
        {
            try
            {
                using (var sr = new StreamReader(_path))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        ParseCSVLineToObjectList(line);
                    }
                    ShowList();
                }
                StartAutodialer();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured: {0}", ex.Message);
            }
        }

        static void ParseCSVLineToObjectList(string line)
        {
            try
            {
                string[] parse = line.Split(',', ';');
                _callInfo = new CallInfo(parse[0], parse[1]);
                _callList.Add(_callInfo);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured: {0}", ex.Message);
            }
        }

        static void ShowList()
        {
            Console.WriteLine();
            foreach (var callListMember in _callList)
            {
                Console.WriteLine("Phone number: \"{0}\", message: \"{1}\".", callListMember.PhoneNumber, callListMember.Message);
            }
            Console.WriteLine();
        }

        static void StartAutodialer()
        {
            _autodialer = new Autodialer(_mySoftphone, _callList, _maxConcurrentCall);
            _autodialer.Start();
        }


        static void ShowGreetingMessage()
        {
            Console.WriteLine("This is a simple Ozeki VoIP SIP SDK demo written in C#.");
            Console.WriteLine("This example will introduce the followings:");
            Console.WriteLine("- asks the user about sip account information. The user can set more SIP accounts to handle multiple phone lines.");
            Console.WriteLine("- asks the user about the amount of calls can be made simultaneously");
            Console.WriteLine("- asks the user about a .csv file path (default option is also provided), parses the file" +
                              "to separate phone numbers from messages");
            Console.WriteLine("- creates CallInfo objects to the provided phone numbers, and uses TextToSpeech feature on the messages to play them to the call.");
            Console.WriteLine("- creates CallHandler objects to handle each call separately.");
            Console.WriteLine("- dials the numbers (while rotating the phone lines) and plays the messages if it's possible.");
            Console.WriteLine("-------------------------------------------------------------------------------");
            Console.WriteLine();
        }


        static void BlockExit()
        {
            while (true)
            {
                Thread.Sleep(10);
            }
        }
    }
}
