using WorkFlowCheck.MAUI.Services.Interfaces;

namespace WorkFlowCheck.MAUI.Pages.System;

public partial class SyncPage : ContentPage
{
    private ISyncService _syncService;
    public SyncPage()
    {
        InitializeComponent();
        _syncService = MauiProgram.ServiceProvider.GetRequiredService<ISyncService>();
    }

    private async void OnSyncClicked(object sender, EventArgs e)
    {
        SyncBtn.IsEnabled = false;
        LoadingIndicator.IsRunning = true;
        LoadingIndicator.IsVisible = true;
        progressLabel.Text = "Szinkronizálás indítása...";
        progressBar.Progress = 0;

        try
        {
            await Task.Run(async () =>
            {
                await _syncService.SyncDatas((percentage, infostring) =>
                {
                    // Direkt UI frissítés
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        progressBar.Progress = percentage / 100;
                        progressLabel.Text = $"{infostring}: {percentage:0.00}%";
                    });
                });
            });

            progressLabel.Text = "Szinkronizálás befejezve!";
            await Shell.Current.GoToAsync("//MainPage");
        }
        catch (Exception ex)
        {
            progressLabel.Text = $"Hiba történt: {ex.Message}";
        }
        finally
        {
            SyncBtn.IsEnabled = true;
            LoadingIndicator.IsVisible = false;
            LoadingIndicator.IsRunning = false;
        }
    }

    private async Task SimulateLongRunningTask(IProgress<double> progress)
    {
        int totalSteps = 50;
        for (int i = 1; i <= totalSteps; i++)
        {
            await Task.Delay(100); // Szimulált hosszú művelet
            double percentage = (double)i / totalSteps * 100;
            progress.Report(percentage);
        }
    }

    protected override bool OnBackButtonPressed()
    {
        Shell.Current.GoToAsync("//MainPage");
        return true;
    }
}