using IpcLibrary.Core;
using IpcLibrary.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IpcLibrary.Client {
    /// <summary>
    /// 客户端扩展方法
    /// </summary>
    public static class IPCClientExtensions {
        /// <summary>
        /// 调用无返回值的方法
        /// </summary>
        public static async Task CallMethodAsync(this IIPCClient client, string targetProcessId, string serviceName, string methodName, params object[] parameters) {
            await client.CallMethodAsync<object>(targetProcessId, serviceName, methodName, parameters);
        }

        /// <summary>
        /// 注册多个服务
        /// </summary>
        public static async Task RegisterServicesAsync(this IIPCClient client, Dictionary<string, object> services) {
            foreach (var kvp in services) {
                await client.RegisterServiceAsync(kvp.Key, kvp.Value);
            }
        }

        /// <summary>
        /// 批量发送通知
        /// </summary>
        public static async Task SendNotificationsAsync(this IIPCClient client, IEnumerable<string> targetProcessIds, string method, params object[] parameters) {
            var tasks = new List<Task>();

            foreach (var processId in targetProcessIds) {
                tasks.Add(client.SendNotificationAsync(processId, method, parameters));
            }

            await Task.WhenAll(tasks);
        }

        /// <summary>
        /// 使用重试机制调用方法
        /// </summary>
        public static async Task<T> CallMethodWithRetryAsync<T>(this IIPCClient client, string targetProcessId, string serviceName, string methodName, int maxRetries = 3, TimeSpan? retryDelay = null, params object[] parameters) {
            var delay = retryDelay ?? TimeSpan.FromSeconds(1);
            Exception lastException = null;

            for (int attempt = 0; attempt <= maxRetries; attempt++) {
                try {
                    return await client.CallMethodAsync<T>(targetProcessId, serviceName, methodName, parameters);
                } catch (Exception ex) {
                    lastException = ex;

                    if (attempt < maxRetries) {
                        await Task.Delay(delay);
                    }
                }
            }

            throw new MethodCallException($"方法调用在 {maxRetries + 1} 次尝试后仍然失败", lastException);
        }
    }
}
