using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components;
using Blazor.Models;
using Blazor.Services;

namespace Blazor.Pages.Admins
{
    public partial class AddAdministrator
    {
        private AdministratorModel administratorModel = new();

        [Inject]
        public IDataService DataService { get; set; }

        [Inject]
        public NavigationManager NavigationManager { get; set; }

        [Inject]
        public ILogger<AddAdministrator> Logger { get; set; }


        private async void HandleValidSubmit()
        {
            administratorModel.HashPassword(administratorModel.HashedPassword);

            await DataService.Add(administratorModel);

            var formData = new List<KeyValuePair<string, string>>();
            formData.Add(new KeyValuePair<string, string>("username", administratorModel.Username));
            formData.Add(new KeyValuePair<string, string>("password", administratorModel.HashedPassword));

            var formContent = new FormUrlEncodedContent(formData);

            string apiUri = "https://trusting-panini.87-106-126-109.plesk.page/api/add/administrator";

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.PostAsync(apiUri, formContent);

                if (response.IsSuccessStatusCode)
                {
                    var responseBody = await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var errorResponse = await response.Content.ReadAsStringAsync();
                }
            }

            Logger.LogInformation("Admin '{administratorsModelName}' added", administratorModel.Username);

            NavigationManager.NavigateTo("administrators");
        }
    }
}
