using System;
using AnyThinkAds.Api;
using Runtime.ADAggregator;
using UnityEngine;

public class ToponAdController : IAdController
{
    public static string LastDetectedArea { get; private set; }
    public static string LastAreaError { get; private set; }
    public static ToponControllerOptions CurrentOptions { get; private set; }

    private Action<bool> _maskAction;
    private Action<string, string> _logEventAction;

    private ADConfig _adConfig;
    private ToponControllerOptions _controllerOptions;
    
    public void Init(ADConfig adConfig, object[] args)
    {
        ToponUnityThread.Initialize();

        _adConfig = adConfig;
        _controllerOptions = ToponControllerOptions.Resolve(adConfig, args);
        CurrentOptions = _controllerOptions;

        ApplyPreInitOptions(_controllerOptions);

        var isDebug = _controllerOptions.Debug ?? false;
        ATSDKAPI.setLogDebug(isDebug);
        ATSDKAPI.initSDK(adConfig.Id , adConfig.Key);
        StartChinaMainlandSdkIfNeeded();
        ApplyPostInitOptions(_controllerOptions);
        if (_controllerOptions.AutoOpenDebuggerUI)
        {
            ShowAndroidTest ();
        }
    }

    public void SetListener(Action<bool> adMaskAction ,Action<string, string> logEventAction)
    {
        _maskAction = adMaskAction;
        _logEventAction = logEventAction;
    }

    public ADPlayer CreateAdPlayer(AD_Type type)
    {
        switch (type)
        {
            case AD_Type.AwardVideo:
                var awardVideoPlayer = new AwardVideoPlayer();
                return awardVideoPlayer.Init(_adConfig.BaseAwardAdKeyValue.value);
            case AD_Type.Splash:
                break;
            case AD_Type.Interaction:
                var interactionPlayer = new InteractionPlayer();
                return interactionPlayer.Init(_adConfig.BaseInteractionAdKeyValue.value);
        }
        return null;
    }

    public void EventLog(string eventTable, string eventValue, string eventMessage = null)
    {
        _logEventAction?.Invoke(eventTable , eventValue);
    }

    public void SetMask(bool isOpen)
    {
        _maskAction?.Invoke(isOpen);
    }

    private void ShowAndroidTest ()
    {
        var debuggerKey = _controllerOptions?.DebuggerKey;
        if (string.IsNullOrWhiteSpace(debuggerKey))
        {
            ATSDKAPI.showDebuggerUI();
        }
        else
        {
            ATSDKAPI.showDebuggerUI(debuggerKey);
        }

        // com.anythink.debug.api.ATDebuggerUITest.showDebuggerUI(this);
// #if UNITY_EDITOR
//         return;
// #elif UNITY_ANDROID
//             //获取Unity的Activity Class
//             using (AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
//             {
//                 //获取对应的实例化对象，这两句都是固定写法
//                 using (AndroidJavaObject activityContext = activityClass.GetStatic<AndroidJavaObject>("currentActivity"))
//                 {
//                     //拿到我自己的工具类并实例化
//                     var testUtils = new AndroidJavaClass("com.anythink.debug.api.ATDebuggerUITest");
//                     //向工具类里的Init方法传入Unity的activity对象用于初始化工具类
//                     testUtils.CallStatic("showDebuggerUI", activityContext);
//                 }
//             }
// #endif
    }

    private void ApplyPreInitOptions(ToponControllerOptions options)
    {
        if (options == null)
        {
            return;
        }

        if (!string.IsNullOrWhiteSpace(options.LocalStrategyAssetPath))
        {
            ATSDKAPI.setLocalStrategyAssetPath(options.LocalStrategyAssetPath);
        }

        if (options.InitCustomMap != null && options.InitCustomMap.Count > 0)
        {
            ATSDKAPI.initCustomMap(options.InitCustomMap);
        }

        var rewardedPlacementId = _adConfig?.BaseAwardAdKeyValue?.value;
        if (!string.IsNullOrWhiteSpace(rewardedPlacementId) &&
            options.RewardedCustomData != null &&
            options.RewardedCustomData.Count > 0)
        {
            ATSDKAPI.setCustomDataForPlacementID(options.RewardedCustomData, rewardedPlacementId);
        }

        if (!string.IsNullOrWhiteSpace(options.Channel))
        {
            ATSDKAPI.setChannel(options.Channel);
        }

        if (!string.IsNullOrWhiteSpace(options.SubChannel))
        {
            ATSDKAPI.setSubChannel(options.SubChannel);
        }

        if (options.SDKArea.HasValue)
        {
            ATSDKAPI.setSDKArea(options.SDKArea.Value);
        }

        if (options.Longitude.HasValue && options.Latitude.HasValue)
        {
            ATSDKAPI.setLocation(options.Longitude.Value, options.Latitude.Value);
        }

        if (options.ExcludeBundleIds != null && options.ExcludeBundleIds.Length > 0)
        {
            ATSDKAPI.setExcludeBundleIdArray(options.ExcludeBundleIds);
        }
    }

    private void ApplyPostInitOptions(ToponControllerOptions options)
    {
        if (options == null)
        {
            return;
        }

        var rewardedPlacementId = _adConfig?.BaseAwardAdKeyValue?.value;
        if (!string.IsNullOrWhiteSpace(rewardedPlacementId) &&
            options.RewardedExcludeAdSourceIds != null &&
            options.RewardedExcludeAdSourceIds.Length > 0)
        {
            ATSDKAPI.setExcludeAdSourceIdArrayForPlacementID(rewardedPlacementId, options.RewardedExcludeAdSourceIds);
        }

        if (options.QueryAreaOnInit)
        {
            ATSDKAPI.getArea(new ToponAreaListener(this, options));
        }
    }

    private static void StartChinaMainlandSdkIfNeeded()
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        try
        {
            if (!ATSDKAPI.isCnSDK())
            {
                return;
            }

            ATSDKAPI.start();
            Debug.Log("[Topon] Called ATSDK.start() for China mainland SDK.");
        }
        catch (Exception exception)
        {
            Debug.LogWarning($"[Topon] Failed to call ATSDK.start(): {exception.Message}");
        }
#endif
    }

    private sealed class ToponAreaListener : ATGetAreaListener
    {
        private readonly ToponAdController _controller;
        private readonly ToponControllerOptions _options;

        public ToponAreaListener(ToponAdController controller, ToponControllerOptions options)
        {
            _controller = controller;
            _options = options;
        }

        public void onArea(string area)
        {
            ToponUnityThread.Post(() =>
            {
                LastDetectedArea = area;
                LastAreaError = null;
                _options?.OnAreaReceived?.Invoke(area);
                _controller?._logEventAction?.Invoke("topon_area", area);
                Debug.Log($"[Topon] Area detected: {area}");
            });
        }

        public void onError(string message)
        {
            ToponUnityThread.Post(() =>
            {
                LastAreaError = message;
                _options?.OnAreaError?.Invoke(message);
                _controller?._logEventAction?.Invoke("topon_area_error", message);
                Debug.LogWarning($"[Topon] Area detect failed: {message}");
            });
        }
    }
}
