using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using wispro.sp.share.webViewObject;
using wispro.sp.web.Auth;

namespace wispro.sp.web.Services
{
    public class AuthService : IAuthService
    {
        private readonly ILocalStorageService localStorageService;
        private readonly HttpClient httpClient;
        private readonly AuthenticationStateProvider authenticationStateProvider;
        private IUserService UserService;

        public AuthService(ILocalStorageService localStorageService, HttpClient httpClient, AuthenticationStateProvider authenticationStateProvider, IUserService UserService)
        {
            this.localStorageService = localStorageService;
            this.httpClient = httpClient;
            this.authenticationStateProvider = authenticationStateProvider;
            this.UserService = UserService;
        }

        public async Task<bool> LoginAsync(loginDto userInfo)
        {
            bool result = false;

            var httpResponse = await httpClient.PostAsJsonAsync<loginDto>($"http://localhost:39476/api/account/Login", userInfo);

            if (httpResponse.IsSuccessStatusCode)
            {
                userToken userToken = await httpResponse.Content.ReadFromJsonAsync<userToken>();
                await localStorageService.SetItemAsync<string>("authToken", userToken.Token);

                ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserAuthentication(userToken.Token);

                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", userToken.Token);
                
                UserService.CurrentUser = new Models.CurrentUser() { Name = userToken.Name};
                
                result = true;
            }

            return result;
        }

        public async Task LogoutAsync()
        {
            await localStorageService.RemoveItemAsync("authToken");
            ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
            httpClient.DefaultRequestHeaders.Authorization = null;
        }
    }
}
