using CrazyStudio.Core.Common.Eitities;
using CrazyStudio.Core.Common.Redis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrazyStudio.Core.Common.Tools.Extensions
{
    public static class RedisExtension
    {
        /// <summary>
        /// 跨域配置
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static async Task<RedisHelper?> AddRedis(this IServiceCollection services, IConfiguration configuration, string myServerClusterTag)
        {
            RedisHelper? redisHelper = null;
            var redisOptions = configuration.GetSection("RedisOptions").Get<RedisOptions>();
            try
            {
                var redisHost = redisOptions?.Host ?? "127.0.0.1";
                var redisPort = redisOptions?.Port ?? "6379";
                var redisPwd = redisOptions?.Password ?? "";
                var redisDbIdx = redisOptions?.DBIndex ?? "0";
                //$"{redisHost}:{redisPort},password={redisPwd}"
                Console.WriteLine("连接Redis缓存服务器");
                var redis = ConnectionMultiplexer.Connect(new ConfigurationOptions
                {
                    KeepAlive = -1,
                    EndPoints = { { IPAddress.Parse(redisHost), int.Parse(redisPort) } },
                    //new EndPointCollection(new IPEndPoint[] { new IPEndPoint(IPAddress.Parse(redisHost), int.Parse(redisPort)) }),
                    Password = redisPwd,
                    AllowAdmin = true
                });

                redis.ConnectionFailed += (sender, e) =>
                {
                    Console.WriteLine("Redis连接失败：" + e.Exception);
                };

                redis.ConnectionRestored += (sender, e) =>
                {
                    //if (redisHelper != null)
                    //{
                    //    await redisHelper.UnsubscribeAllAsync();//Debug
                    //    await redisHelper.SubscribeSystemChannels();
                    //    await redisHelper.SubscribeUsersChannels();
                    //}
                    Console.WriteLine("Redis连接已恢复");
                };

                services.AddSingleton<IConnectionMultiplexer>(redis);

                redisHelper = new RedisHelper(redis, redisDbIdx, myServerClusterTag);

                services.AddSingleton(redisHelper);

                if (redis.IsConnected)
                {
                    Console.WriteLine("连接Redis缓存服务器成功");
                }

                await redisHelper.DeleteRedisCacheForThisServer();

            }
            catch (RedisConnectionException ex)
            {
                Console.WriteLine(ex.Message + "," + ex.StackTrace);

                string logDicPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");//AppDomain.CurrentDomain.BaseDirectory + "logs";//App.HostEnvironment.ContentRootPath;

                string fileName = logDicPath + $"/application-{DateTime.Now:yyyy-MM-dd}.log";
                if (!Directory.Exists(logDicPath))
                {
                    Directory.CreateDirectory(logDicPath);
                }
                if (!File.Exists(fileName))
                {
                    using FileStream fs = File.Create(fileName);
                }
                string str = File.ReadAllText(fileName);
                StringBuilder sb = new StringBuilder();

                sb.Append("\r\n" + DateTime.Now.ToString() + "--------------------------------");
                sb.Append("\r\n" + ex.Message + "\r\n" + ex.StackTrace);

                File.WriteAllText(fileName, str + sb.ToString());
            }

            return redisHelper;
        }
    }
}
