using System.Collections.Generic;
using System.Linq;
using Mapster;
using Resources;
using YGNT.Infrastructure.Resource.Model;

namespace YGNT.Infrastructure.Grpc
{
    /// <summary>
    /// 资源文件
    /// </summary>
    public class GrpcResourcesFile
    {
        /// <summary>
        /// 文件基本信息
        /// </summary>
        /// <param name="resourcesId"></param>
        /// <returns></returns>
        public static ResourceInfo ResourcesFileBaseInfo(string resourcesId)
        {
            var client = new Resources_File.Resources_FileClient(GrpcHost.resourcesChannel);
            var reply = client.ResourcesFileBaseInfor(new ResourcesFileBaseInforParameter() { Id = resourcesId });
            var data = reply.Adapt<ResourceInfo>();
            if (string.IsNullOrEmpty(data.Type))
                data = null;
            return data;
        }

        /// <summary>
        /// 获取文件基本信息（多个）
        /// </summary>
        /// <param name="resourcesIds"></param>
        /// <returns></returns>
        public static Dictionary<string, ResourceInfo> ResourcesFileBaseList(List<string> resourcesIds)
        {
            Dictionary<string, ResourceInfo> keyValues = new Dictionary<string, ResourceInfo>();

            if (resourcesIds == null || !resourcesIds.Any())
                return keyValues;

            var disids = resourcesIds.Distinct();
            var noNullDisids = disids.Where(o => !string.IsNullOrEmpty(o));

            if (noNullDisids.Any())
            {
                Google.Protobuf.Collections.RepeatedField<string> ts = new Google.Protobuf.Collections.RepeatedField<string>();
                ts.AddRange(noNullDisids);

                ResourcesFileBaseListParameter resourcesFileBaseListParameter = new ResourcesFileBaseListParameter();
                resourcesFileBaseListParameter.Ids.AddRange(noNullDisids);

                var client = new Resources_File.Resources_FileClient(GrpcHost.resourcesChannel);
                var reply = client.ResourcesFileBaseList(resourcesFileBaseListParameter);

                foreach (var item in reply.Result)
                {
                    keyValues.Add(item.Key, item.Value.Adapt<ResourceInfo>());
                }
            }

            var nullIds = disids.Except(keyValues.Select(o => o.Key));
            ResourceInfo grpcResourcesFileBaseInfo = new ResourceInfo();
            foreach (var item in nullIds)
            {
                if (!keyValues.ContainsKey(item ?? string.Empty))
                    keyValues.Add(item ?? string.Empty, grpcResourcesFileBaseInfo);
            }

            return keyValues;
        }

    }
}
