using System;
using UnityEngine;
using GameAnalyticsSDK;

public sealed class AdManager : SingletonMonoBehaviour<AdManager> {

    public static readonly string AD_PLACEMENT_COIN = "coin";
    public static readonly string AD_PLACEMENT_CORNFIELD = "cornfield";
    public static readonly string AD_PLACEMENT_CUSTOMER = "increase_customer";
    public static readonly string AD_PLACEMENT_PERFECT = "perfect_popcorn";
    public static readonly string AD_PLACEMENT_VIP = "vip_customer";
    public static readonly string AD_PLACEMENT_AUTO = "auto_popcorn";
    public static readonly string AD_PLACEMENT_SCROLLGAME = "scroll_game";

    //-- ironSource --//
#if UNITY_IOS
    private static readonly string IRONSOURCE_APP_KEY = "11bc8b5ad";
#else
    private static readonly string IRONSOURCE_APP_KEY = "11bc928bd";
#endif

    private Action<bool> _rewardAdCallback = null;
    private readonly int ASYNC_FRAME_LIMIT = 60;
    private int _async_frame_count = 0;
    private bool _rewardAdOpen = false;
    private bool _rewardAdClose = false;
    private bool _rewardAdFinish = false;
    private float _timeScale = 0.0f;

    private bool _marketPause;
    private bool _cacheSeEnabled;

    void Awake(){
#if UNITY_EDITOR
        return;
#endif
        InitializeRewardedAds();
        
#if DEVELOPMENT_BUILD
        IronSource.Agent.validateIntegration ();
        IronSource.Agent.setAdaptersDebug(true);
#endif
        IronSource.Agent.init (IRONSOURCE_APP_KEY);
    }

    void Start(){
#if UNITY_EDITOR
    return;
#endif
        LoadBannerAds();
        ShowBannerAd();
    }

    void Update (){
        if(_rewardAdOpen){
            _rewardAdOpen = false;
            pauseGame();
        }else if(_rewardAdClose){
            if(_rewardAdFinish){
                _rewardAdClose = false;
                this.RewardAdCallbackClose(_rewardAdFinish);
            }else if(ASYNC_FRAME_LIMIT > _async_frame_count){
                _async_frame_count++;
            }else{
                _rewardAdClose = false;
                this.RewardAdCallbackClose(_rewardAdFinish);
            }
        }
    }

    void OnApplicationPause(bool isPaused) {
        IronSource.Agent.onApplicationPause(isPaused);
    }

    //-- Banners Ads --//

    public void LoadBannerAds(){
        IronSource.Agent.loadBanner(IronSourceBannerSize.SMART, IronSourceBannerPosition.BOTTOM);

    }
    public void ShowBannerAd(){
        IronSource.Agent.displayBanner();
    }
    public void HideBanner(){
        IronSource.Agent.hideBanner();
    }

    public void InitializeRewardedAds(){
	    IronSourceEvents.onRewardedVideoAdOpenedEvent += RewardedVideoAdOpenedEvent;
    	IronSourceEvents.onRewardedVideoAdClosedEvent += RewardedVideoAdClosedEvent;
    	IronSourceEvents.onRewardedVideoAvailabilityChangedEvent += RewardedVideoAvailabilityChangedEvent;
        IronSourceEvents.onRewardedVideoAdStartedEvent += RewardedVideoAdStartedEvent;
        IronSourceEvents.onRewardedVideoAdRewardedEvent += RewardedVideoAdRewardedEvent;
    	IronSourceEvents.onRewardedVideoAdShowFailedEvent += RewardedVideoAdShowFailedEvent;
    }
  	private void RewardedVideoAdOpenedEvent(){
        _rewardAdOpen = true;
    }
	private void RewardedVideoAdClosedEvent(){
        _rewardAdClose = true;
    }
	private void RewardedVideoAvailabilityChangedEvent(bool available){
	}
    private void RewardedVideoAdStartedEvent(){
    }
  	private void RewardedVideoAdRewardedEvent(IronSourcePlacement placement){
        _rewardAdFinish = true;
  	}
	private void RewardedVideoAdShowFailedEvent (IronSourceError error){
        _rewardAdClose = true;
  	}
    public bool IsLoadedRewardVideo(){
#if UNITY_EDITOR
        return !UsayaStorageManager.LoadOrDefault(UsayaStorageFilename.Settings_Data, "DebugAlwaysVideoFailToLoad", false);
#else
        return IronSource.Agent.isRewardedVideoAvailable();
#endif
    }
    public void ShowRewardVideo(Action<bool> callback, string ad_placement = "none"){
#if UNITY_EDITOR
        callback(true);
#else
        _rewardAdCallback = callback;
        if(_rewardAdCallback == null){
            return;
        }else if(IsLoadedRewardVideo()){
            _rewardAdOpen = false;
            _rewardAdFinish = false;
            _rewardAdClose = false;
    		_async_frame_count = 0;
            IronSource.Agent.showRewardedVideo();
#if !DEVELOPMENT_BUILD && !UNITY_EDITOR            
            GameAnalytics.NewAdEvent(GAAdAction.FailedShow, GAAdType.RewardedVideo, "ironsource", ad_placement);
#endif
        }else{
            _rewardAdCallback(false);
        }
#endif
    }
    private void RewardAdCallbackClose(bool success){
        resumeGame();
        _rewardAdCallback(success);
        
        // 広告カウント不具合確認用
        if (_rewardAdClose && !_rewardAdFinish)
        {
            Debug.Log($"_async_frame_count:{_async_frame_count}");
            throw new Exception("RewardAd closed but not finish.");
        }
    }

    private void pauseGame(){
        SoundManager.Instance.PauseBGM();
        SoundManager.Instance.StopSE();
        _cacheSeEnabled = SoundManager.Instance.IsEnabled(SoundType.SE);
        SoundManager.Instance.SaveEnabledSE(false);
        _marketPause = Market.Instance.IsPause.Value;
        Market.Instance.IsPause.Value = true;
        if(Time.timeScale > 0.0f){
            _timeScale = Time.timeScale;            
            // TimeManager.Instance.Stop();
        }
    }
    private void resumeGame(){
        SoundManager.Instance.ReplayBGM();
        SoundManager.Instance.SaveEnabledSE(_cacheSeEnabled);
        // キャッシュしていた元の状態に戻す
        if (Market.Instance.IsPause.Value)
        {
            Market.Instance.IsPause.Value = _marketPause;
        }
        if(_timeScale > 0.0f){
            Time.timeScale = _timeScale;
            // TimeManager.Instance.ChangeTimeScale(_timeScale);
            _timeScale = 0.0f;      
        }
    }

}