using System.Windows.Input;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.MAUI.Services.Interfaces;
using WorkFlowCheck.MAUI.Pages.NFC;

namespace WorkFlowCheck.MAUI.Pages.Security;

public partial class UsersPage : ContentPage
{

    private readonly IUserService _userService;
    private readonly ISyncService _syncService;

    public UsersPage()
    {
        InitializeComponent();
        _userService = MauiProgram.ServiceProvider.GetRequiredService<IUserService>();
        _syncService = MauiProgram.ServiceProvider.GetRequiredService<ISyncService>();
    }

    public ICommand RefreshCommand { get; set; }
    public ICommand PairCommand { get; set; }
    public bool IsRefreshing { get; set; }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        RefreshCommand = new Command(async () => await LoadUsers());
        PairCommand = new Command<MobileUserDTO>(OnPairItem);

        BindingContext = this;
        await LoadUsers();

    }
    private async Task LoadUsers()
    {
        IsRefreshing = true;
        //await _syncService.SyncDatas();
        UsersList.ItemsSource = await _userService.GetAllMobileUserAsync();
        IsRefreshing = false;
        OnPropertyChanged(nameof(IsRefreshing));
    }
    
    private async void OnPairItem(MobileUserDTO mobileUserDTO)
    {
        var UserCode = await NFCWaiter.ShowModalAsync();
        if (!string.IsNullOrEmpty(UserCode))
        {
            if (Navigation.ModalStack.Count > 0)
            {
                await Navigation.PopModalAsync();
            }
            if (mobileUserDTO != null)
            {
                mobileUserDTO.NFCCode = UserCode;
                
                await _userService.UpdateCheckPoint(mobileUserDTO);
                await LoadUsers();
            }
        }
    }
    protected override bool OnBackButtonPressed()
    {
        Shell.Current.GoToAsync("//BaseStockPage");
        return true;
    }
    private async void OnButtonSync(object sender, EventArgs e)
    {
        IsRefreshing = true;
        ButtonSync.IsEnabled = false;

        progressLabel.Text = "Szinkronizálás indítása...";
        progressBar.Progress = 0;

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

            progressLabel.Text = "Szinkronizálás befejezve!";
        }
        catch (Exception ex)
        {
            progressLabel.Text = $"Hiba történt: {ex.Message}";
        }
        finally
        {
            ButtonSync.IsEnabled = true;
            IsRefreshing = false;
        }
    }
}