using Android.App;
using Android.OS;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Text;
using Ozeki.VoIP;
using Android.Content.Res;
using System.IO;
using Android.Text.Method;

namespace _09_PredictiveDialer
{
    [Activity(Label = "DialingActivity")]
    public class DialingActivity : Activity
    {
        Softphone _mySoftphone;
        ConfigStore _configStore;
        Autodialer _autoDialer;
        CallInfo _callInfo;
        List<CallInfo> _callList;

        bool _registered;
        string _filename;
        int _maxConcurrentCall;

        TextView _status;
        TextView _btnLogout;
        TextView _listOfNumbers;
        TextView _listOfAgents;

        Button _btnInteractions;
        Button _btnAddAgent;

        EditText _inputAgentNumber;
        Spinner _maxConcurrentCallSpinner;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_dialing);

            _registered = false;
            InitSoftphone();
            Register();

            _maxConcurrentCall = 0;

            _status = FindViewById<TextView>(Resource.Id.status);

            _listOfNumbers = FindViewById<TextView>(Resource.Id.listOfNumbers);
            _listOfNumbers.MovementMethod = new ScrollingMovementMethod();

            _listOfAgents = FindViewById<TextView>(Resource.Id.listOfAgents);
            _listOfAgents.MovementMethod = new ScrollingMovementMethod();

            _maxConcurrentCallSpinner = FindViewById<Spinner>(Resource.Id.maxConcurrentCallSpinner);
            _btnAddAgent = FindViewById<Button>(Resource.Id.btnAddAgent);
            _inputAgentNumber = FindViewById<EditText>(Resource.Id.inputAgentNumber);

            ReadCSV();
            LoadNumbers();

            _btnLogout = FindViewById<TextView>(Resource.Id.btnLogOut);
            _btnLogout.Click += delegate
            {
                if (_registered)
                {
                    _mySoftphone.Unregister();
                }
                Xamarin.Essentials.Preferences.Clear();
                StartActivity(typeof(MainActivity));
            };

            _btnInteractions = FindViewById<Button>(Resource.Id.btnInteractions);
            _btnInteractions.Click += delegate
            {
                if (_registered)
                {
                    StartAutodialer();
                }
            };

            _btnAddAgent.Click += delegate
            {
                if (_inputAgentNumber.Text != "")
                {
                    AddAgent(_inputAgentNumber.Text);
                    _listOfAgents.Text += String.Format("{0}\n", _inputAgentNumber.Text);
                    _inputAgentNumber.Text = "";
                }
            };
        }

        void InitSoftphone()
        {
            _configStore = ConfigStore.Instance;
            _mySoftphone = new Softphone();
            _mySoftphone.PhoneLineStateChanged += mySoftphone_PhoneLineStateChanged;
            _filename = "ExampleCSV.csv";
            _callList = new List<CallInfo>();
        }

        void ReadCSV()
        {
            try
            {
                AssetManager assets = Application.Context.Assets;
                using (StreamReader reader = new StreamReader(assets.Open(_filename)))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        ParseCSVLineToObjectList(line);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured: {0}", ex.Message);
            }
        }

        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);
            }
        }

        void LoadNumbers()
        {
            StringBuilder listOfNumbers = new StringBuilder();
            foreach (var callListMember in _callList)
            {
                listOfNumbers.Append(String.Format("Phone number: \"{0}\", message: \"{1}\".\n", callListMember.PhoneNumber, callListMember.Message));
            }
            _listOfNumbers.Text = listOfNumbers.ToString();
        }

        void StartAutodialer()
        {
            _maxConcurrentCall = Int32.Parse(_maxConcurrentCallSpinner.SelectedItem.ToString());
            _autoDialer = new Autodialer(_mySoftphone, _callList, _maxConcurrentCall);
            _autoDialer.Start();
        }

        void AddAgent(string member)
        {
            _configStore.AddAgent(member);
            _configStore.AddFreeAgent(member);
        }

        private void mySoftphone_PhoneLineStateChanged(object sender, RegistrationStateChangedArgs e)
        {
            if (e.State == RegState.Error || e.State == RegState.NotRegistered)
            {
                _registered = false;
                _status.Text = "Not registered";
            }
            else if (e.State == RegState.RegistrationSucceeded)
            {
                _registered = true;
                _status.Text = "Registered";
            }
        }

        private void Register()
        {
            bool registrationRequired = true;
            string displayName = Xamarin.Essentials.Preferences.Get("display_name", "");
            string userName = Xamarin.Essentials.Preferences.Get("user_name", "");
            string authenticationId = Xamarin.Essentials.Preferences.Get("authentication_id", "");
            string registerPassword = Xamarin.Essentials.Preferences.Get("register_password", "");
            string domainHost = Xamarin.Essentials.Preferences.Get("domain_host", "");
            int domainPort = Xamarin.Essentials.Preferences.Get("domain_port", 5060);

            _mySoftphone.Register(registrationRequired, displayName, userName, authenticationId, registerPassword,
                domainHost, domainPort);
        }

        public override void OnBackPressed()
        {
            return;
        }
    }
}