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

using spanreed.Server.Data;
using spanreed.Shared;

namespace spanreed.Server.Hubs {
    public class MessageHub : Hub {
        private readonly PrevChat prevChat;
        public MessageHub(PrevChat prevChat) {
            this.prevChat = prevChat;
        }

        public async Task Connect(string room) {
            await Groups.AddToGroupAsync(Context.ConnectionId, room);
        }

        public async Task SendMessage(string author, string content, string room, DateTime timestamp) {
            if (author.Length > 0 && content.Length > 0) {
                if (prevChat.Chats.ContainsKey(room)) {
                    prevChat.Chats[room].Add(new ChatData {Author = author, Content = content, Timestamp = timestamp});
                }
                else {
                    prevChat.Chats.Add(room, new List<ChatData> {new ChatData {Author = author, Content = content, Timestamp = timestamp}});
                }
                await Clients.Group(room).SendAsync("Received", author, content, timestamp);
            }
        }
    }
}