using Blazor.Models;
using Blazor.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;

namespace Blazor.Pages.Admins
{
    public partial class EditAdministrator
    {

        [Parameter]
        public int Id { get; set; }

        private AdministratorModel? administratorModel;

        [Inject]
        public IStringLocalizer<EditAdministrator> Localizer { get; set; }

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

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

        [Inject]
        public required IWebHostEnvironment WebHostEnvironment { get; set; }

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

        private string OldAdminName { get; set; } = "";

        protected override async Task OnInitializedAsync()
        {
            var administrator = await DataService.GetAdminById(Id);
            OldAdminName = administrator.Username;

            administratorModel = new AdministratorModel
            {
                Id = administrator.Id,
                Username = administrator.Username,
                HashedPassword = administrator.HashedPassword
            };
        }

        private async Task HandleValidSubmit()
        {
            if (administratorModel != null)
            {
                administratorModel.HashPassword(administratorModel.HashedPassword);

                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 = API.API_URL + "update/administrator/" + administratorModel.Id + "/" + API.TOKEN;

                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 '{OldAdminModelName}' edited in '{NewAdminModelName}'", OldAdminName, administratorModel.Username);

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