using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Nfc;
using Android.Nfc.Tech;
using Android.OS;
using Com.Lvcheng.Lock.Shared.Nfc.Example.Java;
using NFCLockDemoV2;
using NFCLockDemoV2.Platforms.Android;
using NFCLockDemoV2.ViewModels;
using Microsoft.Maui;
using Microsoft.Maui.Controls;

namespace NFCLockAppV2;

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density, Exported = true)]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { Intent.CategoryLauncher })]
[IntentFilter(new[] { NfcAdapter.ActionNdefDiscovered }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "text/plain")]
public class MainActivity : MauiAppCompatActivity
{
    private NFCHelper? nfcHelper;
    private MainViewModel mainViewModel;
    /*private NfcAdapter? nfcAdapter;
    private PendingIntent? pendingIntent;
    private IntentFilter[]? intentFilters = [];
    private string[][] techLict = new string[1][] { [typeof(NfcA).FullName] };*/

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        // 初始化 NFC Helper
        InitializeNFC();
        /*nfcAdapter = NfcAdapter.GetDefaultAdapter(this);
        pendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.ReceiverReplacePending), PendingIntentFlags.Mutable); */
    }

    private void InitializeNFC()
    {
        if (!TryInitializeNFC())
        {
            // 延迟到UI线程完全准备好后再尝试
            Microsoft.Maui.Controls.Application.Current.Dispatcher.Dispatch(() =>
            {
                TryInitializeNFC();
            });
        }
    }

    private bool TryInitializeNFC()
    {
        if (nfcHelper != null && mainViewModel != null)
            return true;
        
        MainViewModel viewModel = null;
        if (Microsoft.Maui.Controls.Application.Current?.Handler?.MauiContext?.Services != null)
        {
            viewModel = Microsoft.Maui.Controls.Application.Current.Handler.MauiContext.Services.GetService<MainViewModel>();
        }
        
        if (viewModel != null)
        {
            NFCCallbacks nFCCallbacks = new NFCCallbacks(viewModel);
            nfcHelper = new NFCHelper(this, nFCCallbacks);
            return true;
        }

        return false;
    }

    protected override void OnResume()
    {
        base.OnResume();
        // 确保NFC功能在每次恢复时都已初始化
        InitializeNFC();
        nfcHelper.OnResume();
    }

    protected override void OnPause()
    {
        base.OnPause();
        nfcHelper.OnPause();
    }

    protected override void OnNewIntent(Intent intent)
    {
        base.OnNewIntent(intent);
        nfcHelper.OnNewIntent(intent);
    }
}