using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Input;
using JD.Interfaces.Remoting;
using JD.Remoting.Services;
using Plume.Icons;
using Plume.Interfaces.WPF.Actions;
using Plume.Interfaces.WPF.Dialogs;
using Action = Plume.Interfaces.WPF.Actions.Action;
namespace JD.Remoting.WPF.Actions
{
public class ConnectToAction : Action
{
public ConnectToAction()
:base("Connect To...", "Connect the application to a specific endpoint", StandardIcon.Wifi)
{
}
///
public override void TryExecute()
{
var dialogService = Context.DialogManager;
var pluginService = Context.ServiceManager.GetPluginService();
var notificationService = Context.NotificationManager;
var result = dialogService.ShowInputBox("Endpoint", "Please select an endpoint (ip:port, e.g. 168.0.1.24:801)", out var endPointString);
if (result.StandardButton == StandardButton.Ok)
{
try
{
if (!Regex.IsMatch(endPointString, @"\b(\d{1,3}\.){3}\d{1,3}\:\d{1,8}\b", RegexOptions.IgnoreCase))
{
throw new ArgumentException("Please provide an endpoint in the valid format ip:port, e.g. 168.0.1.24:801");
}
var elements = endPointString.Split(':');
var endPoint = new EndPointId(elements[0], int.Parse(elements[1]));
pluginService.Start(endPoint);
Task.Delay(500).ContinueWith(task =>
{
foreach (IPlugin plugin in pluginService)
{
if (!plugin.IsConnected)
{
notificationService.ShowError($"Unable to connect the plugin ({plugin.Name}) to the engine; target: {pluginService.EndPointId}");
}
}
});
}
catch (Exception exception)
{
Context.Application.Logger.Error($"Unable to connect to {endPointString}. {exception}", exception);
notificationService.ShowError($"Unable to connect to {endPointString}. Details: {exception.Message}");
}
}
}
///
public override bool CanExecute()
{
IPluginService pluginService = Context.ServiceManager.GetPluginService();
return pluginService.Any() && !pluginService.All(p => p.IsConnected);
}
}
}