using Blazored.LocalStorage;
using Blazor.Services;
using Blazored.Modal.Services;
using Blazor.ViewClasses;
using System.Text;
using Microsoft.JSInterop;
using Microsoft.AspNetCore.Components;
using Blazorise.DataGrid;
using ChoETL;
using Microsoft.AspNetCore.Components.Forms;
using Blazor.Modals;
using Blazored.Modal;

namespace Blazor.Pages.Chapters;
public partial class Chapters
{
    public List<Chapter> chapters;

    private int totalChapter;

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

    [CascadingParameter]
    public IModalService Modal { get; set; }

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

    [Inject]
    public HttpClient Http { get; set; }

    [Inject]
    public ILocalStorageService LocalStorage { get; set; }

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


    private async void OnDelete(int id)
    {
        var parameters = new ModalParameters();
        parameters.Add(nameof(Chapter.Id), id);

        var modal = Modal.Show<DeleteConfirmation>("Delete Confirmation", parameters);
        var result = modal.Result;

        if (result.IsCanceled)
        {
            return;
        }

        await DataService.Delete(id);

        // Reload the page
        NavigationManager.NavigateTo("chapters", true);
    }


    //protected override async Task OnAfterRenderAsync(bool firstRender)
    //{
    //    if (!firstRender)
    //    {
    //        return;
    //    }
    //}

    private async Task OnReadData(DataGridReadDataEventArgs<Chapter> e)
    {
        if (e.CancellationToken.IsCancellationRequested)
        {
            return;
        }

        var response = Http.GetFromJsonAsync<Chapter[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;

        if (!e.CancellationToken.IsCancellationRequested)
        {
            chapters = new List<Chapter>(response); // an actual data for the current page
            totalChapter = chapters.Count;
            var currentData = await LocalStorage.GetItemAsync<Chapter[]>("data");
            if (currentData == null || currentData.Length != chapters.Count)
            {
                var originalData = Http.GetFromJsonAsync<Chapter[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;
                await LocalStorage.SetItemAsync("data", originalData);
            }
        }
    }

    private async void Export()
    {
        StringBuilder sb = new StringBuilder();
        HttpResponseMessage response = await Http.GetAsync("https://trusting-panini.87-106-126-109.plesk.page/api/chapters");
        var json = await response.Content.ReadAsStringAsync();
        using (var jsonFile = ChoJSONReader.LoadText(json))
        {
            using (var csvFile = new ChoCSVWriter(sb).WithFirstLineHeader())
            {
                csvFile.Write(jsonFile);
            }
        }

        var sentFile = new MemoryStream(Encoding.UTF32.GetBytes(sb.ToString()));

        using (var streamRef = new DotNetStreamReference(stream: sentFile))
        {
            await IJSRuntime.InvokeVoidAsync("downloadFileFromStream", "data.csv", streamRef);
        }
    }

    private async Task SingleUpload(InputFileChangeEventArgs e)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            await e.File.OpenReadStream().CopyToAsync(ms);
            var bytes = ms.ToArray();
            string s = Encoding.UTF8.GetString(bytes);

            char[] invalidChars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '\r', '\n', ',', ' ' };

            List<string> filteredStrings = new List<string>();
            StringBuilder filteredString = new StringBuilder();

            foreach (var c in s)
            {
                if (!invalidChars.Contains(c))
                {
                    filteredString.Append(c);
                }
                else
                {
                    if (filteredString.Length > 0)
                    {
                        filteredStrings.Add(filteredString.ToString());
                        filteredString.Clear();
                    }
                }
            }

            if (filteredString.Length > 0)
            {
                filteredStrings.Add(filteredString.ToString());
            }
            foreach (var filteredStr in filteredStrings)
            {
                var formData = new List<KeyValuePair<string, string>>();
                formData.Add(new KeyValuePair<string, string>("name", filteredStr));


                var formContent = new FormUrlEncodedContent(formData);

                string apiUri = "https://trusting-panini.87-106-126-109.plesk.page/api/add/chapter";

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