using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Nfc;
using Android.OS;


namespace WorkFlowCheck.MAUI
{
    [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
    public class MainActivity : MauiAppCompatActivity
    {
        NfcAdapter nfcAdapter;
        PendingIntent pendingIntent;
        static Action<string> _onTagRead;

        protected async override void OnDestroy()
        {
            SecureStorage.Default.Remove("WFCUser");
            SecureStorage.Default.Remove("AuthToken");
            base.OnDestroy();
        }
        
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            nfcAdapter = NfcAdapter.GetDefaultAdapter(this);
            pendingIntent = PendingIntent.GetActivity(this, 0,
                            new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.SingleTop),
                            Build.VERSION.SdkInt >= BuildVersionCodes.S ? PendingIntentFlags.Mutable : PendingIntentFlags.UpdateCurrent);

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

            if (intent.Action == NfcAdapter.ActionTagDiscovered)
            {
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
                var id = tag?.GetId();
                if (id != null)
                {
                    var hex = BitConverter.ToString(id).Replace("-", "");
                    _onTagRead?.Invoke(hex);
                }
            }
        }

        public void StartNfc(Action<string> onTagRead)
        {
            _onTagRead = onTagRead;
            if (nfcAdapter.IsEnabled)
            {
                nfcAdapter?.EnableForegroundDispatch(this, pendingIntent, null, null);
            }
        }
       
        public void StopNfc()
        {
            _onTagRead = null;
            //if (!IsFinishing && !IsDestroyed)
            //{
            //    nfcAdapter?.DisableForegroundDispatch(this);
            //}
        }
    }
}
