import { SdkDefault } from "./SdkDefault";

export class SdkAndroid extends SdkDefault {
    private className = "com/utils/Sdk";
    private lastShowInterAdTime: number = 0;
    private _rewardVideoCallback: (result: boolean) => void = null;
    private _purchaseCallback: (result: boolean, purchases?: any) => void = null;
    private _purchasesCallback: (result: boolean, purchases?: any[]) => void = null;

    private skus = [
        'coins1200',
        'coins2700',
        'coins4400',
        'coins6800'
    ];

    /**
     * 开始游戏
     * @param cb 
     */
    startGame(cb?: Function): void {
        cc.log('SdkDefault startGame.');
        cb && cb();
        setTimeout(() => {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "removeLaunchImage", "()V");
        }, 0.3);//延迟一会删除splash
    }

    share(imageBase64: any, text: string) {
        jsb.reflection.callStaticMethod(this.className, "share", "(Ljava/lang/String;Ljava/lang/String;)V", imageBase64, text);
    }

    logEvent(eventName: string, params?: { [key: string]: string }) {
        let extraStr = params ? JSON.stringify(params) : JSON.stringify({});
        jsb.reflection.callStaticMethod(this.className, "logEvent", "(Ljava/lang/String;ILjava/lang/String;)V", eventName, extraStr);
    }

    /////////////////////////////////////////////////////Purchase
    getProducts(cb?: (catalog: Array<any>) => void) {
        cb && cb(null);
    }

    getPurchases(cb?: (result: boolean, purchases?: any[]) => void) {
        this._purchasesCallback = cb;
        this._purchaseCallback = null;
        jsb.reflection.callStaticMethod(this.className, "queryInventoryByJS", "(Ljava/lang/String;Ljava/lang/String;)V", JSON.stringify(this.skus), JSON.stringify([]));
    }

    getPriceCallback = function(json){
        if (!this.priceObj){
            this.priceObj = {};
        }
    
        cc.log('price json = ', json);
        let obj = json;//JSON.parse(json);
    
        if (obj){
            let _keys = Object.keys(obj);
            for(let i = 0, len = _keys.length; i < len; ++i){
                this.priceObj[_keys[i]] = obj[_keys[i]];//记录本地价格
            }
    
            let node = cc.find('Canvas');
            if (node){
                node.emit('updateSkuPrice', this.priceObj);
            }
        }
    };

    purchaseProduct(sku: string, cb?: (result: boolean, purchase?: any) => void) {
        this._purchaseCallback = cb;
        this._purchasesCallback = null;
        jsb.reflection.callStaticMethod(this.className, "purchase", "(Ljava/lang/String;)V", sku);
        // cb && cb(true, { purchaseToken: sku })
    }

    //从js返回的数据
    purchaseCallback(isSuccess: boolean, sku: string) {
        if (this._purchaseCallback) {
            setTimeout(() => {
                this._purchaseCallback(isSuccess, { purchaseToken: sku });
            }, 100);
        }

        if (this._purchasesCallback) {
            setTimeout(() => {
                this._purchasesCallback(isSuccess, [{ productID: sku, purchaseToken: sku }]);
            }, 100);
        }
    }

    consumePurchase(token: string, cb?: (result: boolean) => void) {
        cb && cb(true);//不需要消耗，在java端已处理，直接返回
    }

    isPaymentReady(cb?: (result: boolean) => void) {
        cb && cb(true);
    }


    //Ads
    showInterAd() {
        cc.log('show InterAd');
        if (Date.now() - this.lastShowInterAdTime > 30000) {//最少间隔30秒
            jsb.reflection.callStaticMethod(this.className, "showInterAd", "()V");
            this.lastShowInterAdTime = Date.now();
        }
    }

    showVideoAd(cb?: (result: boolean) => void) {
        this._rewardVideoCallback = cb;
        cc.log('show VideoAd');
        jsb.reflection.callStaticMethod(this.className, "showRewardVideo", "()V");
        // cb && cb(true);
    }

    setRewardVideoShowCallback(result: boolean) {
        if (this._rewardVideoCallback) {
            setTimeout(() => {
                this._rewardVideoCallback(result);
            }, 100);
        }
    }

    vibrate(milliSeconds: number) {
        jsb.reflection.callStaticMethod(this.className, "vibrate", "(I)V", milliSeconds);
    }

    isVibrateSupport(): boolean {
        return jsb.reflection.callStaticMethod(this.className, "isVibrateSupport", "()Z");
    }

    rate() {
        jsb.reflection.callStaticMethod(this.className, "rate", "()V");
    }

    postScore(best: number) {
        jsb.reflection.callStaticMethod(this.className, "uploadScore", "(I)V", best);
    }

    showLeaderboard(score: number){
        jsb.reflection.callStaticMethod(this.className, "showLeaderboard", "(I)V", score);
    }
}
