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;
using Blazor.Pages.Admins;

namespace Blazor.Pages.Questions;

public partial class Questions
{
    public List<Question> questions;

    private int totalQuestion;

    [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(Question.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("questions", true);
    }


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        // Do not treat this action if is not the first render
        if (!firstRender)
        {
            return;
        }

        var currentData = await LocalStorage.GetItemAsync<Question[]>("data");

        // Check if data exist in the local storage
        if (currentData == null)
        {
            // this code add in the local storage the fake data (we load the data sync for initialize the data before load the OnReadData method)
            var originalData = Http.GetFromJsonAsync<Question[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;
            await LocalStorage.SetItemAsync("data", originalData);
        }
    }

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

        // When you use a real API, we use this follow code
        //var response = await Http.GetJsonAsync<Item[]>( $"http://my-api/api/data?page={e.Page}&pageSize={e.PageSize}" );
        var response = (await Http.GetFromJsonAsync<Question[]>($"{NavigationManager.BaseUri}fake-question.json")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList();

        if (!e.CancellationToken.IsCancellationRequested)
        {
            totalQuestion = (await Http.GetFromJsonAsync<List<Question>>($"{NavigationManager.BaseUri}fake-question.json")).Count;
            questions = new List<Question>(response); // an actual data for the current page
        }
    }

    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/chapters";

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

