Korero – Rev 2

Subversion Repositories:
Rev:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Korero.Communication;
using Korero.Properties;
using Korero.Serialization;
using Korero.Utilities;
using Serilog;

namespace Korero.Selection
{
    public partial class AvatarSelectionForm : Form
    {
        #region Public Events & Delegates

        public event EventHandler<AvatarSelectedEventArgs> AvatarSelected;

        #endregion

        #region Private Delegates, Events, Enums, Properties, Indexers and Fields

        private readonly CancellationToken _cancellationToken;

        private readonly CancellationTokenSource _cancellationTokenSource;

        private readonly dynamic _data;

        private readonly MqttCommunication _mqttCommunication;

        #endregion

        #region Constructors, Destructors and Finalizers

        public AvatarSelectionForm()
        {
            InitializeComponent();

            _cancellationTokenSource = new CancellationTokenSource();
            _cancellationToken = _cancellationTokenSource.Token;
        }

        public AvatarSelectionForm(MqttCommunication mqttCommunication, dynamic data) : this()
        {
            _data = data;
            _mqttCommunication = mqttCommunication;
        }

        public AvatarSelectionForm(MqttCommunication mqttCommunication) : this()
        {
            _mqttCommunication = mqttCommunication;
        }

        /// <summary>
        ///     Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && components != null)
            {
                components.Dispose();
            }

            base.Dispose(disposing);
        }

        #endregion

        #region Event Handlers

        private void AvatarSelectionForm_Load(object sender, EventArgs e)
        {
            Utilities.WindowState.FormTracker.Track(this);
        }

        private async void Button1_Click(object sender, EventArgs e)
        {
            var firstName = textBox1.Text;
            var lastName = textBox2.Text;

            var data = new Dictionary<string, string>
            {
                {"command", "batchavatarnametokey"},
                {"group", Settings.Default.Group},
                {"password", Settings.Default.Password},
                {"avatars", new CSV(new[] {$"{firstName} {lastName}"})},
                {"sift", new CSV(new[] {"take", "1"})}
            };

            var callback = await _mqttCommunication.SendCommand(new Command(data), _cancellationToken);

            if (callback == null || !callback.Success)
            {
                if (callback != null)
                {
                    Log.Warning("Command {Command} has failed with {Error}.",
                        callback.Command, callback.Error);
                }

                return;
            }

            if (!callback.Contains($"{firstName} {lastName}"))
            {
                return;
            }

            var avatarSelection = new AvatarSelection(firstName, lastName);

            AvatarSelected?.Invoke(this, new AvatarSelectedEventArgs(avatarSelection, _data));

            Close();
        }

        private void RegionListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (regionListBox.SelectedIndex > -1)
            {
                friendsListBox.ClearSelected();
            }
        }

        private void FriendsListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (friendsListBox.SelectedIndex > -1)
            {
                regionListBox.ClearSelected();
            }
        }

        private void FriendsListBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            EmitSelection((ListBox) sender, e);
        }

        private void RegionListBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            EmitSelection((ListBox) sender, e);
        }

        private async void AvatarSelectionForm_Shown(object sender, EventArgs e)
        {
            await Task.WhenAll(RetrieveFriendsList(), RetrieveRegionAvatars());
        }

        private void AvatarSelectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            _cancellationTokenSource.Cancel();
        }

        #endregion

        #region Public Methods

        public void EmitSelection(ListBox listBox, MouseEventArgs e)
        {
            var index = listBox.IndexFromPoint(e.Location);
            if (index == ListBox.NoMatches)
            {
                return;
            }

            var avatarSelection = (AvatarSelection) listBox.Items[index];
            AvatarSelected?.Invoke(this, new AvatarSelectedEventArgs(avatarSelection, _data));

            Close();
        }

        #endregion

        #region Private Methods

        private async Task RetrieveFriendsList()
        {
            var data = new Dictionary<string, string>
            {
                {"command", "getfriendslist"},
                {"group", Settings.Default.Group},
                {"password", Settings.Default.Password},
                {"sift", new CSV(new[] {"each", "2"})}
            };

            var callback = await _mqttCommunication.SendCommand(new Command(data), _cancellationToken);

            if (callback == null || !callback.Success)
            {
                if (callback != null)
                {
                    Log.Warning("Command {Command} has failed with {Error}.",
                        callback.Command, callback.Error);
                }

                return;
            }

            foreach (var item in callback.Data)
            {
                friendsListBox.InvokeIfRequired(listBox => { listBox.Items.Add(new AvatarSelection(item)); });
            }
        }

        private async Task RetrieveRegionAvatars()
        {
            var data = new Dictionary<string, string>
            {
                {"command", "getavatarpositions"},
                {"group", Settings.Default.Group},
                {"password", Settings.Default.Password},
                {"entity", "region"},
                {"sift", new CSV(new[] {"each", "3"})}
            };

            var callback = await _mqttCommunication.SendCommand(new Command(data), _cancellationToken);

            if (callback == null || !callback.Success)
            {
                if (callback != null)
                {
                    Log.Warning("Command {Command} has failed with {Error}.",
                        callback.Command, callback.Error);
                }

                return;
            }

            foreach (var item in callback.Data)
            {
                regionListBox.InvokeIfRequired(listBox => { listBox.Items.Add(new AvatarSelection(item)); });
            }
        }

        #endregion

    }
}

Generated by GNU Enscript 1.6.5.90.