using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BinaryDad.Coding.Hubs
{
    public class CodeHub : Hub
    {
        private static readonly IDictionary<string, User> users = new Dictionary<string, User>(StringComparer.OrdinalIgnoreCase);

        public Task UpdateCode(string user, int index, string code)
        {
            return Clients.All.SendAsync("ReceiveCode", user, index, code);
        }

        public async Task SaveName(string name, string color)
        {
            users[Context.ConnectionId].Name = name;
            users[Context.ConnectionId].Color = color;

            await Clients.All.SendAsync("UsersList", users);
        }

        public override async Task OnConnectedAsync()
        {
            users[Context.ConnectionId] = new User
            {
                Name = ""
            };

            await Clients.All.SendAsync("UsersList", users);

            await base.OnConnectedAsync();
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            users.Remove(Context.ConnectionId);

            await Clients.All.SendAsync("UsersList", users);

            await base.OnDisconnectedAsync(exception);
        }
    }
}