using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;

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;
using System.Text.Json;

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

        public AuthService(ILocalStorageService localStorageService, IHttpService 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.Post<userToken>($"account/Login", userInfo);

            if (httpResponse.StatusCode != System.Net.HttpStatusCode.NotFound)
            {
                userToken userToken = httpResponse;
                await localStorageService.SetItemAsync<userToken>("authToken", userToken);

                ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserAuthentication(userToken.Token);
                
                result = true;
            }
            //System.Threading.Thread.Sleep(1000);
            return result;
        }

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

        public async Task<List<string>> GetRoles(string resourceId)
        {
            
            var httpResponse = await httpClient.Get<List<string>>($"account/GetRoles?ResourceId={resourceId}");
            return httpResponse;
            
        }
    }
}
