using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using hive.adkit.daro;
using Game;

public class HiveAdKitManager : MonoBehaviour
{

    // delegate format
    public delegate void onAdKitManagerEvent(bool isSuccess);

    // delegate list
    // HIVE SDK AuthV4 delegates
    static onAdKitManagerEvent onAdKitManagerInit;

    public bool isInitialized = false;

    private const string TAG = "HiveAdKitManager";

    static HiveAdKitManager _instance = null;	// 싱글톤 객체
    private static object _syncobj = new object();
	private static bool appIsClosing = false;

    HIVEAdKit.Banner banner;
    HIVEAdKit.Interstitial interstitial;

#if UNITY_ANDROID
    private string bannerUnitId = "87499610-55a8-4534-82d3-43a1dec91543";
    private string interstitialUnitId = "824e6ee2-ecba-4ddb-9d80-c78fbea7e81d";
#elif UNITY_IOS
    private string bannerUnitId = "700bd259-939c-4b74-b4cb-37d83250bbef";
    private string interstitialUnitId = "dc3070cb-5a46-45de-969f-0e6d570819ed";
#else
    private string bannerUnitId = "";
    private string interstitialUnitId = "";
#endif    

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    static public HiveAdKitManager shared {
		get {
            if (appIsClosing)
                return null;

			lock (_syncobj)  
            {  
				if (_instance == null) {
					_instance = FindObjectOfType<HiveAdKitManager> ();
					if (_instance == null) {
						//create gameobject and add component postbox
						GameObject obj = new GameObject ();
						obj.name = "HiveAdKitManager";
						_instance = obj.AddComponent<HiveAdKitManager> ();
						DontDestroyOnLoad (obj);
					}
				}
			}
			return _instance;
		}
    }

    protected virtual void OnApplicationQuit()
    {
        // release reference on exit
        appIsClosing = true;
    }

    public void InitPlugin() 
    {
        HIVEAdKit.InitPlugin();
    }

    public void AdKitInitialize(onAdKitManagerEvent listener) 
    {

        onAdKitManagerInit = listener;
        HIVEAdKit.Initialize(isSuccess =>
        {
            isInitialized = true;
            onAdKitManagerInit(isSuccess);
            ReadyAds();
        });
    }

    public void ReadyAds()
    {
        if (onAdKitManagerInit != null)
        {
            onAdKitManagerInit = null;
        }
        readyBanner();
        readyInterstitial();
    }

#region Banner
    public void readyBanner(EventHandlers eventHandlers = null) 
    {
        if(eventHandlers == null) {
            eventHandlers = new EventHandlers.Builder()
                                                .OnAdLoaded(OnBannerLoadCB)
                                                .OnAdFailed(OnBannerFailCB)
                                                .Build();
        }

        Debug.Log("hideBanner readyBanner");
        banner = HIVEAdKit.Banner.Initialize(bannerUnitId, BannerPosition.Bottom, eventHandlers);
    }

    public void loadBanner()
    {
        if(banner != null) HIVEAdKit.Banner.Load(banner, "Banner-Load");
    }

    public void hideBanner()
    {
        if(banner != null)
        {
            Debug.Log("hideBanner banner is not null");
            HIVEAdKit.Banner.Destroy(banner);
            banner = null;
            readyBanner(); // 배너는 재사용이 불가하므로 객체 초기화
        }
    }

    public HIVEAdKit.Banner GetAdKitBanner() 
    {
        return banner;
    }

    private void OnBannerLoadCB() 
    {
        Debug.Log(TAG + "::OnBannerLoadCB");
    }

    private void OnBannerFailCB(int errorCode, string errorMessage) 
    {
        Debug.Log(TAG + "::OnBannerFailCB errorCode " + errorCode);
        Debug.Log(TAG + "::OnBannerFailCB errorMessage " + errorMessage);
    }
#endregion

#region Interstitial
    public void readyInterstitial(EventHandlers eventHandlers = null) 
    {
        if(eventHandlers == null) {
            eventHandlers = new EventHandlers.Builder()
                                                .OnAdLoaded(OnInterstitialLoadCB)
                                                .OnAdClosed(OnInterstitialCloseCB)
                                                .OnAdFailed(OnInterstitialFailCB)
                                                .Build();
        }

        interstitial = HIVEAdKit.Interstitial.Initialize(interstitialUnitId, eventHandlers);

        loadInterstitial(); // 전면 광고는 초기화와 동시에 로드 진행
    }

    public HIVEAdKit.Interstitial GetAdKitInterstitial() 
    {
        return interstitial;
    }

    private void OnInterstitialLoadCB() {
        Debug.Log(TAG + "::OnInterstitialLoadCB");
    }

    private void OnInterstitialFailCB(int errorCode, string errorMessage) 
    {
        Debug.Log(TAG + "::OnInterstitialFailCB errorCode " + errorCode);
        Debug.Log(TAG + "::OnInterstitialFailCB errorMessage " + errorMessage);
    }

    private void OnInterstitialCloseCB() 
    {
        Debug.Log(TAG + "::OnInterstitialCloseCB");
        
        GameManager gameManager = FindObjectOfType<GameManager>();
        if (gameManager != null) {
            gameManager.retryGame();

            loadInterstitial(); // 전면 광고 닫히면 다음 광고 다시 로드 시작
        } else {
            Debug.LogWarning("GameManager not found in scene");
        }
    }

    public void loadInterstitial()
    {
        if(interstitial != null) HIVEAdKit.Interstitial.Load(interstitial, "Interstitial-Load");
    }

    public void showInterstitial()
    {
        if(interstitial != null && HIVEAdKit.Interstitial.IsLoaded(interstitial)) HIVEAdKit.Interstitial.Show(GetAdKitInterstitial(), "Interstitial-Show");
    }
#endregion
}