import { InputBlock } from "../misc/InputBlock";
import { HTML5, PREVIEW } from "cc/env";
import { EventMgr } from "./EventMgr";
import { Debug } from "../util/Debug";
import { H5Ad } from "../sdk/h5/H5Ad";

const Tag: string = 'zh:AdMgr.ts'
const Inter_Ad_Cooling_Time: number = 30000

export class AdMgr {

    private static ad: any = null
    private static lastInterAdShowTime: number = 0

    public static init() {
        if (HTML5) this.ad = H5Ad
        this.ad?.init()
    }

    public static showBanner(): void {
        Debug.Log(Tag, 'showBanner PREVIEW='+PREVIEW)
        if (PREVIEW) {
            Debug.Log(Tag, '预览模式下展示Banner')
            return
        }
        this.ad?.showBanner()
    }

    public static hideBanner(): void {
        Debug.Log(Tag, 'hideBanner PREVIEW='+PREVIEW)
        if (PREVIEW) {
            Debug.Log(Tag, '预览模式下隐藏Banner')
            return
        }
        this.ad?.hideBanner()
    }

    /**
     * 就直接发奖励
     * @param onSuccess 
     * @param onFail 
     * @param onError 
     * @returns 
     */
    public static showRewardedVideo(onSuccess: Function, onFail?: Function, onError?: Function): void {
           
            Debug.Log(Tag, '预览模式下播放激励视频直接发放奖励')
            onSuccess && onSuccess(1)
            return


        //下面是原始的代码
        // Debug.Log(Tag, 'showRewardedVideo PREVIEW='+PREVIEW)
        // if (PREVIEW) {
        //     Debug.Log(Tag, '预览模式下播放激励视频直接发放奖励')
        //     onSuccess && onSuccess(1)
        //     return
        // }
        // InputBlock.setActive(2)
        // Debug.Log(Tag, 'showRewardedVideo 111')
        // this.ad?.showRewardedVideo(onSuccess, onFail, onError)
        // Debug.Log(Tag, 'showRewardedVideo 222')
        
    }

    public static showInterstitialAd(onSuccess?: Function, onFail?: Function, onError?: Function): void {
        Debug.Log(Tag, 'showInterstitialAd PREVIEW='+PREVIEW)
        if (PREVIEW) {
            Debug.Log(Tag, '预览模式下展示插屏')
            this.lastInterAdShowTime = Date.now()
            onSuccess && onSuccess()
            return
        }
        if (Date.now() - this.lastInterAdShowTime < Inter_Ad_Cooling_Time) {
            Debug.Log(Tag, '插屏冷却中')
            return
        }
        this.lastInterAdShowTime = Date.now()
        InputBlock.setActive(2)
        if (!onFail) onFail = () => { EventMgr.emit('OpenUI', 'UIToast', { data: '激励视频播放未完成' }) }
        if (!onError) onError = () => { EventMgr.emit('OpenUI', 'UIToast', { data: '暂时没有合适的广告' }) }
        this.ad?.showInterstitialAd(onSuccess, onFail, onError)
    }

    public static showPortalAd(): void {
        Debug.Log(Tag, 'showPortalAd PREVIEW='+PREVIEW)
        if (PREVIEW) {
            Debug.Log(Tag, '预览模式下展示互推盒子')
            return
        }
        InputBlock.setActive(2)
        this.ad?.showPortalAd()
    }

}
