
export default class AdsFB {
    private rewardId: string = null;
    private interId: string = null;

    private loadingInterstitialState: string = null;
    private preloadedInterstitial: FBInstant.AdInstance = null;

    private loadingRewardedVideoState: string = null;
    private preloadedRewardedVideo: FBInstant.AdInstance = null;

    constructor(rewardId: string, interId: string) {
        this.rewardId = rewardId;
        this.interId = interId;
    }

    private log(str: string) {
        console.log(str);
    }

    private createInterstitialAd() {
        if (this.loadingInterstitialState != null) {
            return;
        }

        let supportedAPIs = FBInstant.getSupportedAPIs();
        if (supportedAPIs.indexOf('getInterstitialAdAsync') !== -1) {
            //
            // Preload Rewarded
            //
            FBInstant.getInterstitialAdAsync(
                this.interId, // Your Ad Placement Id
            ).then((interstitial) => {
                // Load the Ad asynchronously
                this.preloadedInterstitial = interstitial;
                this.loadingInterstitialState = 'loading';
                return this.preloadedInterstitial.loadAsync();
            }).then(() => {
                this.loadingInterstitialState = 'load_comlepte';
                this.log("interstitial preloaded.")
            }).catch((err) => {
                // FBManager.preloadedInterstitial = null;
                // FBManager.loadingInterstitialState = LoadInterstitialState.none;
                this.loadingInterstitialState = 'load_error';
                this.log('interstitial failed to preload:' + err.message);
            });

        } else {
            this.log('Ads not supported in this session');
        }
    }

    public loadInterstitial() {
        this.log("start loadInterstitial");

        if (this.loadingInterstitialState === 'load_comlepte' ||
            this.loadingInterstitialState === 'loading') {
            return;//如果正在加载，或加载成功则返回，重复加载会引起错误
        }

        if (this.preloadedInterstitial) {//已经存在视频实例则去服务器加载
            this.log("preloadedInterstitial start loadAsync.")
            this.loadingInterstitialState = 'loading';
            this.preloadedInterstitial.loadAsync().then(() => {
                this.log("loadInterstitial preloaded.")
                this.loadingInterstitialState = 'load_comlepte';
            }).catch((err) => {
                // FBManager.preloadedInterstitial = null;
                // FBManager.loadingInterstitialState = LoadInterstitialState.none;
                this.loadingInterstitialState = 'load_error';
                this.log('loadInterstitial failed to preload:' + err.message);
            });
        } else {//如果实例不存在，则去创建一个新视频实例
            this.createInterstitialAd();
        }
    }

    showInterstitial(cb?: (result: boolean) => void) {
        this.log("start showInterstitial");

        if (this.loadingInterstitialState !== 'load_comlepte') {
            this.log("showInterstitial: not load.. try loading ... ");
            this.loadInterstitial();
            cb && cb(false);
            return;//如果在加载则不重新调用加载，否则FB会引起 正在 load() 中的错误
        }

        this.preloadedInterstitial.showAsync()
            .then(() => {
                // Perform post-ad success operation
                this.log("showInterstitial ok.");
                cb && cb(true);
                this.loadingInterstitialState = null;
                this.preloadedInterstitial = null;//播放完成需置为空，下次会创建新实例，每个实例每次播放只能使用一次
                this.loadInterstitial();//request next
            }).catch((e) => {
                this.log("showInterstitial error : " + e.message);
                cb && cb(false);
                this.loadInterstitial();//request next 播放出错需重新加载，实例保持不需释放
            });
    }

    createRewardedAd() {
        this.log("start createRewardedAd");

        if (this.loadingRewardedVideoState !== null) {
            return;//只接受新创建调用，否则会引起太多个实例调用问题
        }

        {
            let supportedAPIs = FBInstant.getSupportedAPIs();
            if (supportedAPIs.indexOf('getRewardedVideoAsync') !== -1) {
                //
                // Preload Rewarded
                //
                FBInstant.getRewardedVideoAsync(
                    this.rewardId, // Your Ad Placement Id
                ).then((rewarded) => {
                    // Load the Ad asynchronously
                    this.preloadedRewardedVideo = rewarded;
                    this.loadingRewardedVideoState = 'loading';
                    return this.preloadedRewardedVideo.loadAsync();
                }).then(() => {
                    this.loadingRewardedVideoState = 'load_comlepte';
                    this.log("Rewarded video preloaded.")
                }).catch((err) => {
                    // FBManager.preloadedRewardedVideo = null;
                    // FBManager.loadingRewardedVideoState = LoadRewardState.none;
                    this.loadingRewardedVideoState = "load_error";
                    this.log('Rewarded video failed to preload:' + err.message);
                });

            } else {
                this.log('Ads not supported in this session');
            }
        }
    };

    loadRewardedVideo() {
        this.log("start loadRewardedVideo");

        if (this.loadingRewardedVideoState === 'load_comlepte' ||
            this.loadingRewardedVideoState === 'loading') {
            return;//如果正在加载，或加载成功则返回，重复加载会引起错误
        }

        if (this.preloadedRewardedVideo) {//已经存在视频实例则去服务器加载
            this.log("preloadedRewardedVideo start loadAsync.")
            this.loadingRewardedVideoState = 'loading';
            this.preloadedRewardedVideo.loadAsync().then(() => {
                this.log("loadRewardedVideo video preloaded.")
                this.loadingRewardedVideoState = 'load_comlepte';
            }).catch((err) => {
                // FBManager.preloadedRewardedVideo = null;
                // FBManager.loadingRewardedVideoState = LoadRewardState.none;
                this.loadingRewardedVideoState = 'load_error';
                this.log('loadRewardedVideo video failed to preload:' + err.message);
            });
        } else {//如果实例不存在，则去创建一个新视频实例
            this.createRewardedAd();
        }
    };

    showRewardedVideo(cb?: (result: boolean) => void) {
        this.log("start showRewardedVideo");

        if (this.loadingRewardedVideoState !== 'load_comlepte') {
            this.log("showRewardedVideo: not load.. try loading ... ");
            cb && cb(false);
            this.loadRewardedVideo();
            return;//如果在加载则不重新调用加载，否则FB会引起 正在 load() 中的错误
        }

        this.preloadedRewardedVideo.showAsync()
            .then(() => {
                // Perform post-ad success operation
                this.log("showRewardedVideo ok.");
                cb && cb(true);
                this.loadingRewardedVideoState = null;
                this.preloadedRewardedVideo = null;//播放完成需置为空，下次会创建新实例，每个实例每次播放只能使用一次
                this.loadRewardedVideo();//request next
            }).catch((e) => {
                this.log("showRewardedVideo error : " + e.message);
                this.loadingRewardedVideoState = null;
                this.preloadedRewardedVideo = null;
                cb && cb(false);

                this.loadRewardedVideo();//request next 播放出错需重新加载，实例保持不需释放
            });
    };

    isRewardedVideoAvailable() {
        return this.loadingRewardedVideoState === 'load_comlepte';
    };
}
