Korero – Rev 2

Subversion Repositories:
Rev:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Korero.Chat;
using Korero.Communication;
using Korero.Properties;
using Korero.Serialization;
using Korero.Utilities;
using Serilog;

namespace Korero.Friendship
{
    public partial class FriendshipForm : Form
    {
        #region Private Delegates, Events, Enums, Properties, Indexers and Fields

        private readonly CancellationToken _cancellationToken;

        private readonly CancellationTokenSource _cancellationTokenSource;

        private readonly MainForm _mainForm;

        private readonly MqttCommunication _mqttCommunication;

        #endregion

        #region Constructors, Destructors and Finalizers

        public FriendshipForm()
        {
            InitializeComponent();

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

        public FriendshipForm(MainForm mainForm, MqttCommunication mqttCommunication) : this()
        {
            _mainForm = mainForm;
            _mqttCommunication = mqttCommunication;
            _mqttCommunication.NotificationReceived += MqttCommunication_NotificationReceived;
        }

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

            _mqttCommunication.NotificationReceived -= MqttCommunication_NotificationReceived;
            base.Dispose(disposing);
        }

        #endregion

        #region Event Handlers
        private void FriendshipForm_Load(object sender, EventArgs e)
        {
            Utilities.WindowState.FormTracker.Track(this);
        }
        private void MqttCommunication_NotificationReceived(object sender, MqttNotificationEventArgs e)
        {
            switch (e.Notification["notification"])
            {
                case "friendship":
                    switch (e.Notification["action"])
                    {
                        case "update":
                            var firstName = e.Notification["firstname"];
                            var lastName = e.Notification["lastname"];

                            var rights = new CSV(e.Notification["rights"]).ToArray();

                            dataGridView1.InvokeIfRequired(dataGridView =>
                            {
                                foreach (DataGridViewRow row in dataGridView.Rows)
                                {
                                    if ((string) row.Cells[0].Value != $"{firstName} {lastName}")
                                    {
                                        continue;
                                    }

                                    row.Cells[4].Value = Array.IndexOf(rights, "CanSeeOnMap") != -1;
                                    row.Cells[5].Value = Array.IndexOf(rights, "CanModifyObjects") != -1;

                                    switch (e.Notification["status"])
                                    {
                                        case "online":
                                            row.DefaultCellStyle.BackColor = Settings.Default.FriendOnlineHighlight;
                                            break;
                                        case "offline":
                                            row.DefaultCellStyle.BackColor = Color.Empty;
                                            break;
                                    }
                                }
                            });


                            break;
                    }

                    break;
            }
        }

        private async void FriendshipForm_Shown(object sender, EventArgs e)
        {
            var data = new Dictionary<string, string>
            {
                {"command", "getfriendslist"},
                {"group", Settings.Default.Group},
                {"password", Settings.Default.Password}
            };

            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 friend in CsvStride(callback.Data, 2))
            {
                var name = friend[0];
                var id = friend[1];

                data = new Dictionary<string, string>
                {
                    {"command", "getfrienddata"},
                    {"group", Settings.Default.Group},
                    {"password", Settings.Default.Password},
                    {"agent", id},
                    {
                        "data", new CSV(new[]
                        {
                            "CanModifyMyObjects",
                            "CanModifyTheirObjects",
                            "CanSeeMeOnline",
                            "CanSeeMeOnMap",
                            "CanSeeThemOnline",
                            "CanSeeThemOnMap",
                            "IsOnline"
                        })
                    }
                };

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

                var canModifyMyObjects = callback["CanModifyMyObjects"].FirstOrDefault();
                var canModifyTheirObjects = callback["CanModifyTheirObjects"].FirstOrDefault();
                var canSeeMeOnline = callback["CanSeeMeOnline"].FirstOrDefault();
                var canSeeMeOnMap = callback["CanSeeMeOnMap"].FirstOrDefault();
                var canSeeThemOnline = callback["CanSeeThemOnline"].FirstOrDefault();
                var canSeeThemOnMap = callback["CanSeeThemOnMap"].FirstOrDefault();
                var isOnline = callback["IsOnline"].FirstOrDefault();

                dataGridView1.InvokeIfRequired(dataGridView =>
                {
                    var index = dataGridView.Rows.Add();
                    dataGridView.Rows[index].Cells[0].Value = name;

                    dataGridView.Rows[index].Cells[1].Value = canSeeMeOnline == "True";
                    dataGridView.Rows[index].Cells[2].Value = canSeeMeOnMap == "True";
                    dataGridView.Rows[index].Cells[3].Value = canModifyMyObjects == "True";

                    dataGridView.Rows[index].Cells[4].Value = canSeeThemOnMap == "True";
                    dataGridView.Rows[index].Cells[5].Value = canModifyTheirObjects == "True";

                    if (isOnline == "True")
                    {
                        dataGridView.Rows[index].DefaultCellStyle.BackColor = Settings.Default.FriendOnlineHighlight;
                    }
                });
            }
        }

        private void ChatToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var index = dataGridView1.CurrentCell.RowIndex;
            if (index == -1)
            {
                return;
            }

            var selectedItem = (string) dataGridView1.Rows[index].Cells[0].Value;

            if (_mainForm.ChatForm != null)
            {
                _mainForm.ChatForm.CreateOrSelect(selectedItem);
                return;
            }

            _mainForm.ChatForm = new ChatForm(_mainForm, _mqttCommunication);
            _mainForm.ChatForm.Closing += ChatForm_Closing;
            _mainForm.ChatForm.Show();
            _mainForm.ChatForm.CreateOrSelect(selectedItem);
        }

        private void ChatForm_Closing(object sender, CancelEventArgs e)
        {
            if (_mainForm.ChatForm == null)
            {
                return;
            }

            _mainForm.ChatForm.Closing -= ChatForm_Closing;
            _mainForm.ChatForm.Dispose();
            _mainForm.ChatForm = null;
        }

        private async void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 1 || e.ColumnIndex > 3)
            {
                return;
            }

            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

            // Apply checkstate.
            var value = (bool) dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = !value;

            var name = (string) dataGridView1.Rows[e.RowIndex].Cells[0].Value;
            var firstName = name.Split(' ')[0];
            var lastName = name.Split(' ')[1];

            var rights = new List<string>();
            for (var i = 1; i < 4; ++i)
            {
                if (!(bool) dataGridView1.Rows[e.RowIndex].Cells[i].Value)
                {
                    continue;
                }

                switch (i)
                {
                    case 1:
                        rights.Add("CanSeeOnline");
                        break;
                    case 2:
                        rights.Add("CanSeeOnMap");
                        break;
                    case 3:
                        rights.Add("CanModifyObjects");
                        break;
                }
            }

            var data = new Dictionary<string, string>
            {
                {"command", "grantfriendrights"},
                {"group", Settings.Default.Group},
                {"password", Settings.Default.Password},
                {"firstname", firstName},
                {"lastname", lastName},
                {"rights", new CSV(rights)}
            };

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

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

        #endregion

        #region Private Methods

        private static IEnumerable<string[]> CsvStride(string input, int stride)
        {
            var i = 0;
            return new CSV(input).Select(s => new {s, num = i++})
                .GroupBy(t => t.num / stride, t => t.s)
                .Select(g => g.ToArray());
        }

        #endregion


    }
}

Generated by GNU Enscript 1.6.5.90.