using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using AOT;
using UnityEngine;

public class UnityPhoneUtils
{
    private UnityPhoneUtils() { }
    private static readonly UnityPhoneUtils singleInstance = new UnityPhoneUtils();
    public static UnityPhoneUtils Instance
    {
        get
        {
            return singleInstance;
        }
    }

    private AndroidJavaObject activity;
    public AndroidJavaObject GetActivity()
    {
        if (activity == null)
        {
            var unityPlayer = new AndroidJavaClass(
            "com.unity3d.player.UnityPlayer");
            activity = unityPlayer.GetStatic<AndroidJavaObject>(
           "currentActivity");
        }
        return activity;
    }

    private string device_iOS = "";
    private string idfa_iOS = "";

    private AndroidJavaObject phoneUtil;
    private AndroidJavaObject GetPhoneUtil()
    {
        if (phoneUtil == null)
        {
            phoneUtil = new AndroidJavaClass("com.ym.common.UnityPhoneUtils").CallStatic<AndroidJavaObject>("getInstance");
        }
        return phoneUtil;
    }


#if UNITY_IOS

 /// <summary>
    /// 声明交互方法
    /// </summary>
    /// <param name="resultString"></param>
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate void ResultHandlerIDFA(string resultString);
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate void ResultHandlerDevice(string resultString);

    /// <summary>
    /// 接受交互值  在iOS代码中调用 resultHandlerIDFA("传值");
    /// </summary>
    /// <param name="resultStr"></param>
    [MonoPInvokeCallback(typeof(ResultHandlerIDFA))]
    static void resultHandlerIDFA(string resultStr)
    {
        Instance.idfa_iOS = resultStr;
    }

    [MonoPInvokeCallback(typeof(ResultHandlerDevice))]
    static void resultHandlerDevice(string resultStr)
    {
        Instance.device_iOS = resultStr;
    }

#endif

    public string GetDevice()
    {
        if (null != Constant.Instance.device && !Constant.Instance.device.Equals(""))
        {
            return Constant.Instance.device;
        }
        Constant.Instance.device = PlayerPrefs.GetString("user_device", "");
        if (Constant.Instance.device.Equals(""))
        {
#if UNITY_EDITOR
            Constant.Instance.device = "debug_test_002";
#elif UNITY_ANDROID
             Constant.Instance.device = GetPhoneUtil().Call<string>("getDeviceId", GetActivity());
#elif UNITY_IOS

            Constant.Instance.device = Constant.Instance.device;

#endif

            PlayerPrefs.SetString("user_device", Constant.Instance.device);
        }
        Debug.unityLogger.Log("GetDevice " + Constant.Instance.device);
        return Constant.Instance.device;
    }


}
