using ColorControl.Shared.Common; using ColorControl.Shared.Contracts; using Newtonsoft.Json; using System.Diagnostics; namespace ColorControl.UI.Services; public class RpcUiClientOptions { public int Timeout { get; set; } = PipeUtils.DefaultTimeout; } public class RpcUiClientService(NotificationService? notificationService) { public string? LastErrorMessage { get; private set; } public async Task CallAsync(string serviceName, string method, params object?[] arguments) { var rpcMessage = new SvcRpcMessage { ServiceName = serviceName, MethodName = method, Arguments = arguments }; var timeout = Debugger.IsAttached ? 60000 : PipeUtils.DefaultTimeout; return await SendRpcMessageAsync(rpcMessage, timeout, pipeName: PipeUtils.MainPipe); } public async Task CallGenericBoolResultAsync(string serviceName, string method, params object?[] arguments) { var rpcMessage = new SvcRpcMessage { ServiceName = serviceName, MethodName = method, Arguments = arguments }; var timeout = Debugger.IsAttached ? 60000 : PipeUtils.DefaultTimeout; var result = await SendRpcMessageAsync(rpcMessage, timeout, pipeName: PipeUtils.MainPipe); if (result?.Result == true) { return true; } if (result?.ErrorMessages.Count > 0 && notificationService != null) { await notificationService.SendNotificationDirect(new NotificationDto(result.ErrorMessages.First(), Constants.Danger)); } return false; } public async Task CallWithOptionsAsync(string serviceName, string method, RpcUiClientOptions options, params object?[] arguments) { var rpcMessage = new SvcRpcMessage { ServiceName = serviceName, MethodName = method, Arguments = arguments }; return await SendRpcMessageAsync(rpcMessage, options.Timeout, pipeName: PipeUtils.MainPipe); } private async Task SendRpcMessageAsync(SvcRpcMessage message, int timeout = PipeUtils.DefaultTimeout, string pipeName = PipeUtils.ServicePipe) { var messageJson = JsonConvert.SerializeObject(message); var resultJson = await PipeUtils.SendMessageAsync(messageJson, timeout, pipeName); if (resultJson == null) { notificationService?.SendNotification(new NotificationDto("Unknown communication error", Constants.Danger)); return default; } var resultMessage = JsonConvert.DeserializeObject(resultJson); if (resultMessage?.Data == null) { LastErrorMessage = resultMessage?.ErrorMessage ?? "Unknown communication error"; if (notificationService != null) { await notificationService.SendNotificationDirect(new NotificationDto(LastErrorMessage, Constants.Danger)); } return default; } LastErrorMessage = null; var result = JsonConvert.DeserializeObject(resultMessage.Data); return result; } }