using Blazored.Toast.Configuration;
using Blazored.Toast.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using System.Text;
using System.Text.Json;
using ReAct_PME.WebUI.ServicesUI;

namespace ReAct_PME.WebUI
{
    public static class PagesInitializer
    {
        /// <summary>
        /// Vérifie la connexion uniquement
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="authStateprov"></param>
        /// <param name="navigation"></param>
        /// <returns></returns>
        public static bool VerifConnexion(AuthService authService, AuthenticationStateProvider authStateprov, NavigationManager navigation)
        {


            // Vérification si utilisateur est connecté 
            try
            {
                var customAuthStateProvider = (CustomAuthenticationStateProvider)authStateprov;
                bool bByauthStateprov = customAuthStateProvider.User!.Identity!.IsAuthenticated;
                bool bByAuthService = (authService.Token != null && authService.Token != "");

                if (!bByAuthService && bByauthStateprov)
                {
                    authService.SetToken(customAuthStateProvider.Token!);
                }


                if ((!bByauthStateprov && !bByAuthService) || customAuthStateProvider.Token == "")
                {
                    navigation.NavigateTo("/login");
                    return false;
                }
                return true;

            }
            catch 
            {
                return false;
            }

        }

        /// <summary>
        /// Verification des droits d'accès à l"endpoint
        /// </summary>
        /// <param name="authStateprov"></param>
        /// <param name="navigation"></param>
        /// <param name="http"></param>
        /// <param name="toastService"></param>
        /// <param name="apiEndpoint"></param>
        /// <returns></returns>
        public static async Task<string> VerifConnexionAndRules(AuthenticationStateProvider authStateprov, NavigationManager navigation, HttpClient http, IToastService toastService, string apiEndpoint)
        {



            try
            {
                // Vérification si utilisateur est connecté 
                var customAuthStateProvider = (CustomAuthenticationStateProvider)authStateprov;
                if (customAuthStateProvider.User == null)
                {
                    //navigation.NavigateTo("/login");
                    return "";
                }


                if (!customAuthStateProvider.User!.Identity!.IsAuthenticated)
                {
                    navigation.NavigateTo("/login");
                    return "";
                }

                // Vérification des droits d'accès
                var response = await http.GetAsync(apiEndpoint);
                if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
                {
                    toastService.ShowError("Erreur : Vous n'avez pas les droits pour cette action.", settings =>
                    {
                        settings.Timeout = 2000;
                        settings.IconType = IconType.None;
                        settings.Position = ToastPosition.BottomCenter;
                    });
                    return "";
                }
                response.EnsureSuccessStatusCode();

                var token1 = customAuthStateProvider.Token;
                string token = "";
                if(token1 != null) token = token1.ToString();

                return token;
            }

            catch (Exception ex)
            { 
                Console.WriteLine(ex.ToString());
                navigation.NavigateTo("/login");
                return ""; 
            }

        }

        /// <summary>
        /// Vérifie la connexion et les droits d'accès à l"endpoint
        /// </summary>
        /// <param name="authStateprov"></param>
        /// <param name="navigation"></param>
        /// <param name="http"></param>
        /// <param name="toastService"></param>
        /// <param name="apiEndpoint"></param>
        /// <param name="method" description="Get pour GetAll et GetById, Post pour CREATE, Put pour UPDATE, Delete pour DELETE"></param>
        /// <returns></returns>
        public static async Task<bool> VerifConnexionAndRules<T>(AuthenticationStateProvider authStateprov, NavigationManager navigation, HttpClient http,
                                                        IToastService toastService, string apiEndpoint, HttpMethod method,
                                                        T item)
        {



            try
            {
                // Vérification si l'utilisateur est connecté 
                var customAuthStateProvider = (CustomAuthenticationStateProvider)authStateprov;
                if (!customAuthStateProvider.User!.Identity!.IsAuthenticated)
                {
                    navigation.NavigateTo("/login");
                    return false;
                }


                // Définition de la requête selon l'opération
                HttpRequestMessage request = new HttpRequestMessage(method, apiEndpoint);
                request.Content = new StringContent(JsonSerializer.Serialize(item), Encoding.UTF8, "application/json");
                var response = await http.SendAsync(request); 

                // Vérifier si l'accès est refusé
                if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
                {
                    toastService.ShowError("Erreur - accès refusé : Vous n'avez pas les droits pour cette action.", settings =>
                    {
                        settings.Timeout = 2000;
                        settings.IconType = IconType.None;
                        settings.Position = ToastPosition.BottomCenter;
                    });
                    return false;
                }

                response.EnsureSuccessStatusCode(); // Vérifie que la réponse est un succès
                return true;
            }

            catch(Exception ex) 
            {
                toastService.ShowError($"Erreur : {ex.Message}.", settings =>
                {
                    settings.Timeout = 2000;
                    settings.IconType = IconType.None;
                    settings.Position = ToastPosition.BottomCenter;
                });
                return false;
            }

        }
    }
}                       
