using Blazor.Models;
using Blazor.Pages.Chapters;
using Blazor.Services;
using Microsoft.AspNetCore.Components;

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

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

        private AdministratorModel administratorModel = new();

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

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

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

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

        private string OldAdminName { get; set; }

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

            // Set the model with the admin
            administratorModel = new AdministratorModel
            {
                Id = administrator.Id,
                Username = administrator.Username,
                HashedPassword = administrator.HashedPassword
            };
        }

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

            await DataService.Update(Id, 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/update/administrator/" + administratorModel.Id;

            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");
        }
    }
}
