using Java.Lang;
using Com.Lvcheng.Lock.Shared.Nfc.Example.Java;
using NFCLockDemoV2.ViewModels;
using Android.Util;
using Exception = System.Exception;

namespace NFCLockDemoV2.Platforms.Android
{
    public class NFCCallbacks
    {
        private readonly MainViewModel mainViewModel;
        private ViewModels.OperationType? Operation => mainViewModel.Operation;
        public NFCCallbacks()
        {
            mainViewModel = Application.Current?.Handler?.MauiContext?.Services.GetService<MainViewModel>();
        }

        public void OnFinished()
        {
            mainViewModel.DeviceId = "--";
            mainViewModel.DeviceRssi = "--";
            mainViewModel.DeviceStatus = "NFC操作完成";
            //mainViewModel.Operation = null;
            mainViewModel.ArcProgress = 0;
        }

        public bool OnLoop(DeviceManagerWrapper? wrapper, long? id, bool? isNew, int? rssi)
        {
            try
            {
                // 更新设备信息
                mainViewModel.DeviceId = id?.ToString() ?? "--";
                mainViewModel.DeviceRssi = rssi?.ToString() ?? "--";

                string password = mainViewModel.Password;

                // 开关锁需要先充电
                if (Operation == ViewModels.OperationType.LOCK || Operation == ViewModels.OperationType.UNLOCK) 
                {
                    while (true) 
                    {
                        Com.Lvcheng.Lock.Shared.Nfc.Result result = wrapper.GetChargeLevel(password);
                        if (result == Com.Lvcheng.Lock.Shared.Nfc.Result.Ok) 
                        {
                            Integer? level = wrapper.MGetChargeLevel();
                            string levelText = level?.ToString() ?? "0";

                            // 在主线程上更新UI
                            mainViewModel.UpdateMessage("充电中（" + levelText + "%)");

                            // 更新进度条
                            if (level != null)
                            {
                                mainViewModel.ArcProgress = level.IntValue();
                            }

                            if (level != null && level.IntValue() >= 100) 
                            {
                                break;
                            }
                        } 
                        else if (result == Com.Lvcheng.Lock.Shared.Nfc.Result.Unauthorized) 
                        {
                            mainViewModel.UpdateMessage("验证失败");
                            // 返回 false 手动结束 NFC 连接
                            return false;
                        } 
                        else 
                        {
                            mainViewModel.UpdateMessage("充电失败");
                            return false;
                        }
                        
                        // 添加短暂延迟以避免过度频繁的循环
                        System.Threading.Thread.Sleep(100);
                    }
                }

                if (Operation != null) 
                {
                    switch (Operation) 
                    {
                        case ViewModels.OperationType.UNLOCK:
                            if (wrapper.Control(password, false) == Com.Lvcheng.Lock.Shared.Nfc.Result.Ok) 
                            {
                                mainViewModel.UpdateMessage("开锁成功");
                            } 
                            else 
                            {
                                mainViewModel.UpdateMessage("开锁失败");
                            }
                            return false;
                            
                        case ViewModels.OperationType.LOCK:
                            if (wrapper.Control(password, true) == Com.Lvcheng.Lock.Shared.Nfc.Result.Ok) 
                            {
                                mainViewModel.UpdateMessage("关锁成功");
                            } 
                            else 
                            {
                                mainViewModel.UpdateMessage("关锁失败");
                            }
                            return false;
                            
                        case ViewModels.OperationType.SET_PASSWORD:
                            if (wrapper.SetKey(password, "") == Com.Lvcheng.Lock.Shared.Nfc.Result.Ok) 
                            {
                                mainViewModel.UpdateMessage("设置密码成功");
                            } 
                            else 
                            {
                                mainViewModel.UpdateMessage("设置密码失败");
                            }
                            return false;
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                Log.Error("NFCCallbacks", "Error in OnLoop: " + ex.Message);
                mainViewModel.UpdateMessage("操作异常: " + ex.Message);
                return false;
            }
        }

        public void OnLost()
        {
            mainViewModel.DeviceId = "--";
            mainViewModel.DeviceRssi = "--";
            mainViewModel.DeviceStatus = "设备连接断开";
            //mainViewModel.Operation = null;
            mainViewModel.ArcProgress = 0;
        }
    }
}