using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aliyun.Api.LogService;
using Aliyun.Api.LogService.Domain.Log;
using Aliyun.Api.LogService.Infrastructure.Protocol;
using GameMessage;
using MrWu.Debug;

namespace Server.AliyunSDK
{
    public class AliyunSLSService : IAliyunBaseService
    {
        private readonly ILogServiceClient mClient;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="client">SLS客户端</param>
        /// <param name="project">项目名称</param>
        public AliyunSLSService(ILogServiceClient client)
        {
            mClient = client;
        }

        #region 日志操作

        /// <summary>
        /// 异步添加多条日志
        /// </summary>
        /// <param name="logstore">日志库</param>
        /// <param name="logs">日志数据</param>
        /// <param name="topic">元数据：这一组数据对应的主题</param>
        /// <param name="source">元数据：来源（如：IP）</param>
        /// <returns></returns>
        public async Task<bool> PutLogsAsync(
            string logstore,
            IList<LogInfo> logs,
            string topic,
            string source)
        {
            return true;
        }

        /// <summary>
        /// 异步查询日志
        /// </summary>
        /// <param name="logstore">日志库</param>
        /// <param name="query">查询语句</param>
        /// <param name="startTime">日志开始时间</param>
        /// <param name="endTime">日志结束时间</param>
        /// <param name="page">分页数据</param>
        /// <returns>查询数据</returns>
        public async Task<List<LogInfo>> QueryLogsAsync(
            string logstore, 
            string query, 
            DateTime startTime, 
            DateTime endTime, 
            DataPage page)
        {
            try
            {
                if (page == null)
                    page = new DataPage();
                
                var startT = (int)new DateTimeOffset(startTime).ToUnixTimeSeconds();
                var endT = (int)new DateTimeOffset(endTime).ToUnixTimeSeconds();
                var request = new GetLogsRequest(logstore, startT, endT)
                {
                    Query = query,
                    Reverse = true,
                    Line = page.PageSize,
                    Offset = (page.PageId - 1) * page.PageSize,
                };
                var response = await mClient.GetLogsAsync(request);
                //Debug.Info($"response:{response.Result.Count} {response.IsSuccess} {response.Error?.ErrorCode}");
                if (!CheckResponse(response))
                {
                    Debug.Error($"SLS API请求失败 Query:{query}");
                }
                var logs = new List<LogInfo>();
                if (response.Result.Logs != null && response.Result.Logs.Count > 0)
                {
                    var ret = response.Result.Logs;
                    for (int i = 0; i < ret.Count; i++)
                    {
                        LogInfo log = new LogInfo
                        {
                            Contents = ret[i]
                        };
                        logs.Add(log);
                    }
                }
                
                return logs;
            }
            catch (Exception ex)
            {
                Debug.Error($"SLS日志查询失败 - LogStore:{logstore}, Query:{query}, ex:{ex}");
                return new List<LogInfo>();
            }
        }

        /// <summary>
        /// 查询日志这段时间的数量分布
        /// </summary>
        public async Task<int> QueryHistogramsAsync(
            string logstore, 
            string query, 
            DateTime startTime, 
            DateTime endTime)
        {
            try
            {
                var startT = (int)new DateTimeOffset(startTime).ToUnixTimeSeconds();
                var endT = (int)new DateTimeOffset(endTime).ToUnixTimeSeconds();
                GetLogHistogramsRequest request = new GetLogHistogramsRequest(logstore, startT, endT)
                {
                    Query = query,
                };
                var response = await mClient.GetHistogramsAsync(request);
                CheckResponse(response);
                int count = response.Result.Histograms?.Sum(x=>x.Count) ?? 0;
                return count;
            }
            catch (Exception e)
            {
                Debug.Error($"SLS日志状态查询失败 - LogStore:{logstore}, Query:{query}, ex:{e.StackTrace}");
            }

            return 0;
        }
        
        #endregion
        
        private bool CheckResponse(IResponse response)
        {
            if (!response.IsSuccess)
            {
                // ？？ 是否重试
                Debug.Error($"SLS API请求失败 Response:{response} 错误：{response.Error}");
                return false;
            }
            return true;
        }
        
        public void Dispose()
        {
        }
    }
}