using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Web;
using Newtonsoft.Json;
using PTCalendar.Business.Events;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace PTCalendar.Blazor.Server
{
    public static class CalendarServiceExtensions
    {
        public static void AddCalendarService(this IServiceCollection services, IConfiguration configuration)
        {            
            services.AddHttpClient<CalendarService>();
        }
    }

    public class CalendarService
    {
        private readonly IHttpContextAccessor _contextAccessor;
        private readonly HttpClient _httpClient;
        private readonly string _calendarListScope = string.Empty;
        private readonly string _calendarListBaseAddress = string.Empty;
        private readonly ITokenAcquisition _tokenAcquisition;

        public CalendarService(ITokenAcquisition tokenAcquisition, HttpClient httpClient, IConfiguration configuration, IHttpContextAccessor contextAccessor)
        {
            _httpClient = httpClient;
            _tokenAcquisition = tokenAcquisition;
            _contextAccessor = contextAccessor;
            _calendarListScope = configuration["PTCalendar.Api:Scope"];
            _calendarListBaseAddress = configuration["PTCalendar.Api:BaseAddress"];
        }

        /// <summary>
        /// Retrieve all todo items
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<CalendarEventInfo>> GetAsync()
        {
            await PrepareAuthenticatedClient();
            var response = await _httpClient.GetAsync($"{ _calendarListBaseAddress}/api/calendarlist");
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var content = await response.Content.ReadAsStringAsync();
                IEnumerable<CalendarEventInfo> calendarEvents = JsonConvert.DeserializeObject<IEnumerable<CalendarEventInfo>>(content);

                return calendarEvents;
            }

            throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}.");
        }

        /// <summary>
        /// Retrieves the Access Token for the Web API.
        /// Sets Authorization and Accept headers for the request.
        /// </summary>
        /// <returns></returns>
        private async Task PrepareAuthenticatedClient()
        {
            var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { _calendarListScope });
            Debug.WriteLine($"access token-{accessToken}");
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

    }
}
