//#define IS_ANDROID
#if UNITY_ANDROID && !UNITY_EDITOR
#define IS_ANDROID
#endif
using UnityEngine;
#if IS_ANDROID
using UnityEngine.Android;
#endif
using TMPro;

public class GloveConnBridge : MonoBehaviour
{
    //private AndroidJavaClass  javaClass;
    private AndroidJavaObject gloveConn;
    //public Transform targetObject;
    public TextMeshProUGUI DebugTextField;

    public string BindAddress = "127.0.0.1";
    public int BindPort = 53451;
    public string UseMACAddress = "";
    public enum Equipment_Type
    {
        Right = 2,
        Left = 1
    }

    public Equipment_Type EquipmentType = Equipment_Type.Left;

    public int BluetoothFPS = 60;

    private string[] permissions = new string[]
    {
        "android.permission.INTERNET",
        "android.permission.BLUETOOTH_SCAN",
        "android.permission.BLUETOOTH_CONNECT",
        "android.permission.BLUETOOTH_ADMIN",
        "android.permission.ACCESS_FINE_LOCATION"
    };

    private int currentIndex = 0;
    private bool is_started = false;
    private bool is_launched = false;

    void Start()
    {
#if IS_ANDROID
        RequestNextPermission();
#endif
    }

#if IS_ANDROID
    private void RequestNextPermission()
    {
        if (currentIndex >= permissions.Length)
        {
            DebugText("All permissions requested");
            OnAllPermissionsGranted(); // run glove gere
            return;
        }

        string permission = permissions[currentIndex];

        if (!Permission.HasUserAuthorizedPermission(permission))
        {
            DebugText($"Requesting permission {permission}");
            Permission.RequestUserPermission(permission);
        }
        else
        {
            DebugText($"Already granted: {permission}");
            currentIndex++;
            RequestNextPermission(); 
        }
    }

    void OnApplicationFocus(bool hasFocus)
    {
        if (hasFocus)
        {
            DebugText("App resumed, checking permission result...");
            if (currentIndex < permissions.Length)
            {
                string permission = permissions[currentIndex];
                if (Permission.HasUserAuthorizedPermission(permission))
                {
                    DebugText($"Granted: {permission}");
                    currentIndex++;
                    RequestNextPermission();
                }
                else
                {
                    DebugText($"Denied: {permission} — can't proceed.");
                }
            }
        }
    }

    private void DebugText(string msg)
    {
        if (DebugTextField != null) DebugTextField.text = msg;
        Debug.Log(msg);
    }

    private void OnAllPermissionsGranted()
    {
        DebugText("Launching GloveConn...");
        if(is_started)return;

        try
        {
            gloveConn = new AndroidJavaObject("com.senso.api.GloveConn");
            DebugText("GloveConn started.");
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject context = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");           
            gloveConn.Call("Start_Worker", context, BindAddress, BindPort);
            is_started = true;
        }
        catch (System.Exception e)
        {
            Debug.LogError("Exception during GloveConn init: " + e);
            DebugText("EXCEPTION: " + e.Message);
        }
    }
#endif


    //[System.Serializable]
    //public class DeviceInfo
    //{
    //    public string address;
    //    public int rssi;
    //    public string type;
    //}

    private int started = 0;
    //private int conn_result = 1000;

    void Update()
    {
#if IS_ANDROID
        if (gloveConn != null)
        {
            if (is_started && !is_launched)
            {
                is_launched = true;
                gloveConn.Call<int>("Start_Connect", UseMACAddress, (int)EquipmentType, BluetoothFPS);
            }

            string log = gloveConn.Call<string>("GetLog");
            if (log.Length > 0) DebugText(log);
        }
#endif
    }
    void OnDestroy()
    {
#if IS_ANDROID
        if (gloveConn != null)
        {
            gloveConn.Call("Stop_Connect", (bool)true);
            gloveConn.Call("Stop_Worker");
        }
        //started = 0;
#endif
    }
}
