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 = 'AdMgr'
const Inter_Ad_Cooling_Time: number = 30000

export class AdMgr {

    private static ad: any = null
    private static lastInterAdShowTime: number = 0
    private _openAd: boolean = true;
    public get openAd(): boolean {
        return this._openAd;
    }
    public set openAd(value: boolean) {
        this._openAd = value;
    }

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

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

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

    public static showRewardedVideo(onSuccess: Function, onFail?: Function, onError?: Function): void {
        if (PREVIEW) {
            Debug.Log(Tag, '预览模式下播放激励视频直接发放奖励')
            onSuccess && onSuccess(1)
            return
        }
        InputBlock.setActive(2)
        this.ad?.showRewardedVideo(onSuccess, onFail, onError)
    }

    public static showInterstitialAd(onSuccess?: Function, onFail?: Function, onError?: Function): void {
        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 {
        if (PREVIEW) {
            Debug.Log(Tag, '预览模式下展示互推盒子')
            return
        }
        InputBlock.setActive(2)
        this.ad?.showPortalAd()
    }

}
