using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Pivotal.Discovery.Client;
using Steeltoe.Common.Discovery;

namespace SignToken
{
    public class PermissionService : IPermissionService
    {
        DiscoveryHttpClientHandler _handler;
        ILogger<PermissionService> _logger;

        /// <summary>
        /// 获取所有权限信息的URL
        /// </summary>
        private const string PERMISSION_URL = "http://signtokenapi/api/values/getpermission";


        public PermissionService(IDiscoveryClient client, ILoggerFactory logFactory) 
        {
            _handler =  new DiscoveryHttpClientHandler(client, logFactory.CreateLogger<DiscoveryHttpClientHandler>());
            _logger =  logFactory.CreateLogger<PermissionService>();
        }

        public async Task<string> GetPermissionAsync()
        {
            var client = GetClient();
            var result = await client.GetStringAsync(PERMISSION_URL);
            _logger.LogInformation("返回的权限信息为: {0}", result);
            return result;
        }

        public string GetPermission()
        {
            var client = GetClient();
            var result = client.GetStringAsync(PERMISSION_URL).Result;
            _logger.LogInformation("返回的权限信息为: {0}", result);
            return result;
        }

        private HttpClient GetClient()
        {
            var client = new HttpClient(_handler, false);
            return client;
        }
    }
}
