using NFCLockDemoV2.ViewModels;

#if IOS
using Foundation;
using NFCManager = NfcLock.Ios.Binding.NFCManager;
#endif

namespace NFCLockDemoV2;

public partial class MainPage : ContentPage
{
    private MainViewModel _mainMainViewModel;
    
#if IOS
    private void SetNFCCallbacks()
    {
        NFCManager.SetLoopCbWithCb((NSString id, bool isNew,int rssi) => {
            _mainMainViewModel.DeviceId = id;
            _mainMainViewModel.DeviceRssi = rssi.ToString();
            return true;
        });
        NFCManager.SetFinishedCbWithCb(() =>
        {
            System.Diagnostics.Debug.WriteLine("finished");
            _mainMainViewModel.DeviceId = "--";
            _mainMainViewModel.DeviceRssi = "--";
            _mainMainViewModel.DeviceStatus = "NFC操作完成";
            _mainMainViewModel.Operation = null;
            _mainMainViewModel.ArcProgress = 0;
        });
        
        NFCManager.SetChargingCbWithCb((NSString res, int level) =>
        {
            System.Diagnostics.Debug.WriteLine($"res: {res}, level: {level}");
            _mainMainViewModel.UpdateMessage($"充电中({level}%)");
            _mainMainViewModel.ArcProgress = level;
        });
        
        NFCManager.SetControllingCbWithCb((NSString res, int progress) =>
        {
            System.Diagnostics.Debug.WriteLine($"res: {res}, progress: {progress}");
            _mainMainViewModel.UpdateMessage($"控制中({progress}%)");
        });
    }
#endif
    
    public MainPage(MainViewModel mainViewModel)
    {
        InitializeComponent();
        _mainMainViewModel = mainViewModel;
        BindingContext = _mainMainViewModel;
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
#if IOS
        SetNFCCallbacks();
#endif
    }
    
    private void LockClicked(object? sender, EventArgs e)
    {
#if IOS
        NFCManager.LockWithPassword(_mainMainViewModel.Password);
        NFCManager.StartScan();
#endif
    }

    private void UnlockClicked(object? sender, EventArgs e)
    {
#if IOS
        NFCManager.UnlockWithPassword(_mainMainViewModel.Password);
        NFCManager.StartScan();
#endif
    }
}