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

namespace Blazor.Pages.Chapters;

public partial class EditChapter
{
    [Parameter]
    public int Id { get; set; }

    private ChapterModel? chapterModel;

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

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

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

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

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

    private string OldChapterName { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var chapter = await DataService.GetById(Id);
        OldChapterName = chapter.Name;

        chapterModel = new ChapterModel
        {
            Id = chapter.Id,
            Name = chapter.Name
        };
    }

    private async Task HandleValidSubmit()
    {
        
        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+"update/chapter/" + chapterModel.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("Chapter '{OldChapterModelName}' edited in '{NewChapterModelName}'", OldChapterName, chapterModel.Name);
        NavigationManager.NavigateTo("chapters");
    }
}
