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

namespace Blazor.Pages.Players
{
    public partial class EditPlayer
    {

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

        private PlayerModel? playerModel;

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


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

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

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

        protected override async Task OnInitializedAsync()
        {
            var player = await DataService.GetPlayerById(Id);

            // Set the model with the admin
            playerModel = new PlayerModel
            {
                Id = player.Id,
                Nickname = player.Nickname,
                HashedPassword = player.HashedPassword
            };
        }

        private async Task HandleValidSubmit()
        {
            playerModel.HashPassword(playerModel.HashedPassword);

            var formData = new List<KeyValuePair<string, string>>();
            formData.Add(new KeyValuePair<string, string>("nickname", playerModel.Nickname));
            formData.Add(new KeyValuePair<string, string>("password", playerModel.HashedPassword));

            var formContent = new FormUrlEncodedContent(formData);

            string apiUri = API.API_URL+"update/player/" + playerModel.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();
                }
            }
            NavigationManager.NavigateTo("players");
        }
    }
}
