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

namespace Blazor.Pages.Chapters;

public partial class AddChapter
{
    private ChapterModel chapterModel = new();

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

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

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

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



    private async Task HandleValidSubmit()
    {
        if (chapterModel != null)
        {
            var formData = new List<KeyValuePair<string, string>>();
            formData.Add(new KeyValuePair<string, string>("name", chapterModel.Name));


            var formContent = new FormUrlEncodedContent(formData);

            string apiUri = API.API_URL + "add/chapter/" + 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("Chapter '{chapterModelName}' added", chapterModel.Name);

            NavigationManager.NavigateTo("chapters");
        }
    }

}
