using Com.Lvcheng.Lock.Shared.Nfc.Kmp;
using Java.Lang;
using NFCLockDemoV2.ViewModels;
using Math = System.Math;

namespace NFCLockDemoV2;

public class AndroidNfcCallBack : Java.Lang.Object, IAndroidNFCCallbacks
{
    private readonly MainViewModel mainViewModel;
    private long startTimestamp;
    
    public AndroidNfcCallBack(MainViewModel mainViewModel)
    {
        this.mainViewModel = mainViewModel;
    }

    public void Charging(Result result, Integer? p1)
    {        
        startTimestamp = System.Diagnostics.Stopwatch.GetTimestamp();
        if (result == Result.Ok)
        {
            var level = p1?.IntValue() ?? 0;
            string levelText = level.ToString();

            var progress = Math.Min(level, 100) / 3 * 2;
            mainViewModel.ArcProgress = progress;
            mainViewModel.UpdateMessage("充电中（" + levelText + "%)");
        }
        else if  (result == Result.Unauthorized)
        {
            mainViewModel.ArcProgress = 0;
            mainViewModel.UpdateMessage("验证失败");
        }
        else
        {
            mainViewModel.UpdateMessage("充电失败");
        }
    }

    public void Controlling(Result result, Integer? p1, Ctrl ctrl)
    {
        var operationType = ctrl == Ctrl.Lock ? "关锁" : "开锁";
        if (result == Result.Ok)
        {
            mainViewModel.OperationElapsed = FormatElapsed(startTimestamp);
            mainViewModel.ArcProgress = 100;
            mainViewModel.UpdateMessage($"{operationType}成功");

        } else if (result == Result.Unauthorized)
        {
            mainViewModel.ArcProgress = 0;
            mainViewModel.UpdateMessage($"验证失败");
        }
        else
        { 
            mainViewModel.ArcProgress = 0;
            mainViewModel.UpdateMessage($"{operationType}失败");
        }
    }

    public void CustomData(Result result, CustomDataConfig config, byte[]? data)
    {
    }

    public void Discovered(long id, bool isNew, Integer? p2)
    {
        // 更新设备信息
        mainViewModel.DeviceId = id.ToString();
        mainViewModel.DeviceRssi = p2?.ToString() ?? "--";
    }

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

    public void SetKey(Result result, string password)
    {
    }
    
    private static string FormatElapsed(long startTimestamp)
    {
        double elapsedMs = (System.Diagnostics.Stopwatch.GetTimestamp() - startTimestamp) * 1000.0 / System.Diagnostics.Stopwatch.Frequency;
        return elapsedMs >= 1000 ? $"{elapsedMs / 1000.0:F2}s" : $"{elapsedMs:F0}ms";
    }
}