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

namespace Blazor.Pages.Players
{
    public partial class AddPlayer
    {
        private PlayerModel playerModel = new();

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

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

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


        private async Task HandleValidSubmit()
        {
            if (playerModel != null)
            {
                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 + "add/player/" + 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");
            }
        }
    }
}
