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 System.Text.RegularExpressions;
using Blazor.Components;
using Microsoft.Extensions.Localization;
using SuperConvert.Extensions;

namespace Blazor.Pages.Questions;

public partial class Questions
{
    public List<Question> questions = new();

    private int totalQuestion;

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


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

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

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

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

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

    [Inject]
    public required 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 = await modal.Result;

        if (result.Cancelled)
        {
            return;
        }

        string apiUri = API.API_URL+"delete/question/" + id + "/" + API.TOKEN;

        using (var httpClient = new HttpClient())
        {
            var response = await httpClient.DeleteAsync(apiUri);

            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();
            }
            else
            {
                var errorResponse = await response.Content.ReadAsStringAsync();
            }
        }

        NavigationManager.NavigateTo("questions", true);
    }

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

        // Calculez l'index de départ pour la pagination
        int page = ((e.Page - 1) * e.PageSize)/10 + 1;

        // Envoyez une requête à l'API pour récupérer les questions de la page actuelle
        var response = await Http.GetFromJsonAsync<Question[]>(API.API_URL + "all/questions/" + API.TOKEN + "/" + page);

        if (!e.CancellationToken.IsCancellationRequested && response != null)
        {
            questions = new List<Question>(response); // an actual data for the current page

            List<Question> selectedQuestions = new List<Question>();
            for (int i = 0; i < questions.Count; i += 4)
            {
                selectedQuestions.Add(questions[i]);
            }
            questions = selectedQuestions;
            if (!response.IsNullOrEmpty())
            {
                totalQuestion = response[0].total_questions;
            }
        }
    }

    private async Task Export()
    {
        StringBuilder sb = new StringBuilder();
        HttpResponseMessage response = await Http.GetAsync(API.API_URL+"questionsExport/"+API.TOKEN);
        var json = await response.Content.ReadAsStringAsync();
        byte[] csv = json.ToCsv(';');
        string csvString = Encoding.Unicode.GetString(csv);
        var sentFile = new MemoryStream(Encoding.Unicode.GetBytes(csvString));
        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.Unicode.GetString(bytes);

            s = s.Replace("\"", string.Empty);
            s = s.Replace("\0", string.Empty);
            var rows = s.Split('\n');
            rows = rows.Skip(1).ToArray();

            foreach (var row in rows)
            {
                var field = row.Split(';');
                field[1] = field[1].Replace(" ", "+");
                var formData = new List<KeyValuePair<string, string>>();
                formData.Add(new KeyValuePair<string, string>("content", field[0]));
                formData.Add(new KeyValuePair<string, string>("answerContent1", field[3]));
                formData.Add(new KeyValuePair<string, string>("answerContent2", field[4]));
                formData.Add(new KeyValuePair<string, string>("answerContent3", field[5]));
                formData.Add(new KeyValuePair<string, string>("answerContent4", field[6]));
                formData.Add(new KeyValuePair<string, string>("idanswergood", field[2]));

                string apiUri = API.API_URL+"chapters/name/"+field[1] + "/" + API.TOKEN;


                var response = await Http.GetAsync(apiUri);

                if (response.IsSuccessStatusCode)
                {
                    var responseBody = await response.Content.ReadAsStringAsync();
                    Match match = Regex.Match(responseBody, @"\d+");
                    int result = int.Parse(match.Value);
                    formData.Add(new KeyValuePair<string, string>("idchapter", result.ToString()));
                }
                else
                {
                    var errorResponse = await response.Content.ReadAsStringAsync();
                    formData.Add(new KeyValuePair<string, string>("idchapter", "Unknown_Chapter_Error"));
                }

                var formContent = new FormUrlEncodedContent(formData);
                apiUri = API.API_URL+"add/question/"+API.TOKEN;

                response = await Http.PostAsync(apiUri, formContent);

                if (response.IsSuccessStatusCode)
                {
                    var responseBody = await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var errorResponse = await response.Content.ReadAsStringAsync();
                }
            }
        }
    }
}

