
import Utils from "../lib/Utils";
import AdsFB from "./AdsFB";
import { SdkDefault } from "./SdkDefault";

/**
 * Facebook 小游戏实现
 */
export class SdkFB extends SdkDefault {
    public static readonly INTER_INTERVAL = 60000;//60S
    private catalog: any = null;
    private paymentReady = false;

    private ads: AdsFB = null;
    private lastShowInterAdTime: number = 0;

    constructor() {
        super();
    }

    startGame(cb?: Function) {
        FBInstant.setLoadingProgress(100);
        FBInstant.startGameAsync().then(() => {
            cc.log("FBInstant start.");
            cb && cb();

            this.initPayment();
            this.createShortcutFB();
            this.showBotSub();
            this.initAds();
        });
    }

    private initAds() {
        this.ads = new AdsFB("213064306863249_213066196863060", "213064306863249_213066613529685");
        this.ads.loadInterstitial();
        this.ads.loadRewardedVideo();
    }

    /**
     * 创建快捷方式
     */
    private createShortcutFB() {
        FBInstant.canCreateShortcutAsync()
            .then(function (canCreateShortcut) {
                if (canCreateShortcut) {
                    FBInstant.createShortcutAsync()
                        .then(function () {
                            // Shortcut created
                        })
                        .catch(function () {
                        });
                }
            });
    }

    private initPayment() {
        //购买回调
        FBInstant.payments.onReady(() => {
            cc.log('Payments Ready!');
            this.paymentReady = true;
        });
    }

    private showBotSub() {
        FBInstant.player.canSubscribeBotAsync().then((can_subscribe) => {
            if (can_subscribe) {
                FBInstant.player.subscribeBotAsync().then(function () {

                    // start game here

                }).catch(function (e) {

                    // and here regardless

                })
            }
        }).catch(function (e) {

            // start game here too, launch the game!

        });
    }

    getPlatform(): string {
        return FBInstant.getPlatform();
    }

    isPaymentReady(cb?: (result: boolean) => void) {
        let isReady = (FBInstant.getPlatform() != 'IOS' && FBInstant.getSupportedAPIs().indexOf('payments.purchaseAsync') != -1 && this.paymentReady);
        cc.log('isPaymentReadyFB -> ', isReady);
        cb && cb(isReady);
    }

    getPurchases(cb?: (result: boolean, purchases?: any[]) => void) {
        FBInstant.payments.getPurchasesAsync().then((purchases) => {
            cc.log(purchases);
            cb && cb(true, purchases);
        }).catch((err) => {
            cb && cb(false);
        });
    }

    purchaseProduct(sku: string, cb?: (result: boolean, purchase?: any) => void) {
        FBInstant.payments.purchaseAsync({
            productID: sku,
            developerPayload: 'lsp',
        }).then((purchase) => {
            cb && cb(true, purchase);
        }).catch((err) => {
            cb && cb(false);
        });
    }

    consumePurchase(token: string, cb?: (result: boolean) => void) {
        FBInstant.payments.consumePurchaseAsync(token).then(() => {
            // Purchase successfully consumed!
            // Game should now provision the product to the player
            cb && cb(true);
        }).catch((err) => {
            cb && cb(false);
        })
    }

    getProducts(cb?: (catalog: Array<any>) => void) {
        if (this.catalog) {
            cb && cb(this.catalog);
            return;
        }

        FBInstant.payments.getCatalogAsync().then((catalog) => {
            this.catalog = catalog;
            cb && cb(catalog);
        }).catch((err) => {
            cb && cb(null);
        });
    }

    getDataAsync(keys: Array<string>): Promise<Object> {
        return FBInstant.player.getDataAsync(keys);
    }

    setDataAsync(data: Object): Promise<void> {
        return FBInstant.player.setDataAsync(data);
    }

    //Ads
    showInterAd() {
        if (Date.now() - this.lastShowInterAdTime > SdkFB.INTER_INTERVAL) {//最少间隔
            this.ads.showInterstitial();
            this.lastShowInterAdTime = Date.now();
        }
    }

    showVideoAd(cb?: (result: boolean) => void) {
        this.ads.showRewardedVideo(cb);
    }

    //System
    onSystemPause(cb?: () => void) {
        FBInstant.onPause(cb);
    }


    /////////////FB
    getPlayerId(): string {
        return FBInstant.player.getID();
    }
    switchGame(appId: string, data?: any) {
        FBInstant.switchGameAsync(appId, data);
    }

    postScore(best: number) {
        //FBInstant.postSessionScore(best);
    }

    share(imageBase64: any, text: string) {
        FBInstant.shareAsync({
            intent: 'INVITE',
            image: imageBase64,
            text: text,
            data: {}
        }).then(() => {

        }).catch((err) => {

        });
    }

    challengeFriend(imageData: any, playerId: string, challengeText: string, callback?: Function, errCb?: Function) {
        FBInstant.context
            .createAsync(playerId)
            .then(() => {
                //console.log(FBInstant.context.getID());
                let customMsg = {
                    cta: {
                        default: 'CHALLENGE',
                    },
                    image: imageData,
                    text: {
                        default: challengeText,
                    },
                };
                this.sendCustomMsg(customMsg,
                    () => {
                        callback && callback();
                    }, errCb);
            }).catch(() => {
                errCb && errCb();
            });
    };

    updateMessageFB(imageBase64: any) {
        let customMsg = {
            cta: {
                default: 'CHALLENGE',
            },
            image: imageBase64,
            text: {
                default: 'Nice Game, I love it.',
            },
        };
        this.sendCustomMsg(customMsg);
    }

    playWithFriend(imageBase64: any, text?: string, callback?: Function, errCb?: Function) {
        FBInstant.context.chooseAsync(
            //     {
            //     filters: ['NEW_CONTEXT_ONLY', 'NEW_PLAYERS_ONLY'],
            //     minSize: 10,
            // }
        ).then(() => {
            let customMsg = {
                cta: {
                    default: 'BEAT ME',
                },
                image: imageBase64,
                text: {
                    default: text || 'Come and beat me!!',
                },
            };
            this.sendCustomMsg(customMsg,
                () => {
                    callback && callback();
                }, errCb);
        },
            (reason) => {
                errCb && errCb();
            });
    }

    /**
     * 发送自定义数据给正在对战的玩家
     * @param {*} data 发送的数据
     * @example
        ```js
        sendCustomMsg();
        ```
    */
    private sendCustomMsg(data: any, callback?: Function, failCallBack?: Function) {
        let formattedData = this.formatData(data)
        FBInstant.updateAsync(formattedData).then(() => {
            if (callback) {
                callback();
            }
        }).catch((err) => {
            if (failCallBack) {
                failCallBack();
            }
        });
    };

    private formatData = function (data: any) {
        return {
            action: (data && data.action) || 'CUSTOM',
            cta: {
                default: (data && data.cta && data.cta.default) ? data.cta.default : "PLAY NOW!",
                localizations: (data && data.cta && data.cta.localizations) ? data.cta.localizations : {
                    zh_CN: (data && data.cta && data.cta.default) ? data.cta.default : "PLAY NOW!",
                    en_US: (data && data.cta && data.cta.default) ? data.cta.default : "PLAY NOW!",
                    en_UK: (data && data.cta && data.cta.default) ? data.cta.default : "PLAY NOW!",
                    zh_TW: (data && data.cta && data.cta.default) ? data.cta.default : "PLAY NOW!",
                    zh_HK: (data && data.cta && data.cta.default) ? data.cta.default : "PLAY NOW!"
                }
            },
            image: (data && data.image) || null,
            text: {
                default: (data && data.text && data.text.default) ? data.text.default : 'default text',
                localizations: (data && data.text && data.text.localizations) ? data.text.localizations : {
                    zh_CN: (data && data.text && data.text.default) ? data.text.default : 'default text',
                    en_US: (data && data.text && data.text.default) ? data.text.default : 'default text',
                    en_UK: (data && data.text && data.text.default) ? data.text.default : 'default text',
                    zh_TW: (data && data.text && data.text.default) ? data.text.default : 'default text',
                    zh_HK: (data && data.text && data.text.default) ? data.text.default : 'default text'
                }
            },
            template: (data && data.template) ? data.template : 'play_turn',//fbapp-config.json中，custom_update_templates中的key之一
            data: (data && data.data) ? data.data : null,
            strategy: (data && data.strategy) ? data.strategy : 'IMMEDIATE',
            notification: (data && data.notification) ? data.notification : 'NO_PUSH',
        }
    };

    vibrate(milliSeconds: number) {
        Utils.vibrate(milliSeconds);
    }

    isVibrateSupport(): boolean {
        return Utils.vibrateSupport && cc.sys.isMobile;
    }

    logEvent(eventName: string, params?: { [key: string]: string }) {
        FBInstant.logEvent(eventName, 1, params);
    }
}
