using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.MAUI.Services.Interfaces;

namespace WorkFlowCheck.MAUI.Pages.System;

public partial class DownloadAPKPage : ContentPage
{
    private ISyncService _syncService;
    private IUserService _userService;
    private UserDTO _currentUser;

    public DownloadAPKPage()
	{
		InitializeComponent();
        _syncService = MauiProgram.ServiceProvider.GetRequiredService<ISyncService>();
        _userService = MauiProgram.ServiceProvider.GetRequiredService<IUserService>();
    }
    override protected async void OnAppearing()
    {
        base.OnAppearing();
        SetInfo();
    }
    private void SetInfo()
    {
        _currentUser = _userService.GetCurrentUser();
        DeviceId.Text = _userService.DeviceId;
        UserInfo.Text = $"{_currentUser?.LastName} {_currentUser?.FirstName}";
    }
    private async void OnSyncClicked(object sender, EventArgs e)
    {
        SyncBtn.IsEnabled = false;
        LoadingIndicator.IsRunning = true;
        LoadingIndicator.IsVisible = true;
        progressLabel.Text = "Letöltés indítása...";
        progressBar.Progress = 0;

        try
        {
            await Task.Run(async () =>
            {
                await _syncService.DownloadAPK((percentage, infostring) =>
                {
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        progressBar.Progress = percentage / 100;
                        progressLabel.Text = $"{infostring}: {percentage:0.00}%";
                    });
                });
            });

            progressLabel.Text = "Letöltés kész!";
            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;
        }
    }
    protected override bool OnBackButtonPressed()
    {
        Shell.Current.GoToAsync("//MainPage");
        return true;
    }
}