import { StorageKey } from "../../game/data/StorageData";

/**
 * Jsb管理类(与安卓Java类或者IOS交互)
 * @description
 * @author 冯聪
 */
export default class JsbSystem {

    /**代码桥在AS中的路径 */
    private static _JSB_ANDROID_PATH: string = "org/cocos2dx/javascript/thirdSdk/ThirdSdkMgr";
    /**代码桥在IOS中的路径 */
    private static _JSB_IOS_PATH: string = "ThirdSdkMgr";

    /**
     * 是否文件存在
     * @param filePath 文件路径 
     * @returns 是否文件存在 boolean
     */
    public static isFileExist(fileName: string): boolean {
        if (cc.sys.os == cc.sys.OS_WINDOWS) {
            return true;
        }
        let filePath = this.getWritablePath() + fileName + ".apk";
        return jsb.fileUtils.isFileExist(filePath);
    }

    /**
     * 获取写入的路径
     * @description 
     * @returns path 写入路径(string)
     */
    public static getWritablePath(): string {
        return jsb.fileUtils.getWritablePath();
    }

    /** 
     * 调用项目工程静态方法
     * @description           调用Android与IOS对应的静态方法
     * @param path            调用路径："org/cocos2dx/javascript/AppActivity"：java中的包名（.换成/）+class文件名，就当是路径好了
     * @param methodName      调用的方法名：必须public static
     * @param methodSignature 方法签名：“(Ljava/lang/String;)Ljava/lang/String;”：（）内的是调用的java方法的参数类型，（）外面的是返回值类
     * @param parameters      参数：是java方法需要传入的参数（可以多个，与methodSignature中（）内的数量和类型一一对应）
     */
    public static callStaticMethod(path: string, methodName: string, methodSignature: string, ...parameters: any): any {
        jsb.reflection.callStaticMethod(path, methodName, methodSignature, ...parameters);
    }

    /**
     * Java调用返回测试
     * @description 自定义功能 JavaToCocos
     */
    public static backTest() {

    }

    /**
     * 更新设备信息
     * @description 自定义功能 JavaToCocos
     * @param info  info(Java返回)
     */
    public static updateDeviceInfo(info) {
        mk.console.log("updateDeviceInfo" + cc.sys.os, info)
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            gData.appData.updateDeviceInfo(info);
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {

        }
    }

    /**
     * 获取设备信息
     * @description 自定义功能 CocosToJava
     */
    public static getDeviceInfo() {
        mk.console.log("getDeviceInfo", cc.sys.os)
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "getDeviceInfo", "()V");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            this.callStaticMethod(this._JSB_IOS_PATH, "getDeviceInfo", "");
        }
        else {
            gData.appData.getDeviceInfoCompelete = true;
        }
    }

    /**
     * 获取包名
     * @description 自定义功能 CocosToJava
     * @returns     packName 包名
     */
    public static getPackageName() {
        let packName = '';
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            packName = this.callStaticMethod(this._JSB_ANDROID_PATH, "getPackageName", "()Ljava/lang/String;");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            packName = this.callStaticMethod("CsjAdReward", "getPackageName", "");
        }
        return packName;
    }

    /** 
     * 获取微信appid
     * @description 自定义功能 CocosToJava
     * @returns     appid 
     */
    public static getWxAppId() {
        let appid = "";
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            appid = this.callStaticMethod(this._JSB_ANDROID_PATH, "getWxAppId", "()Ljava/lang/String;");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            appid = this.callStaticMethod("CsjAdReward", "getWxAppId", "",);
        }
        return appid;
    }

    /**
     * 获取广告渠道和相关id
     * @description 自定义功能 CocosToJava
     * @returns     str 
     */
    public static getAdvertisingChannel(): string {
        let str = "";
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            str = this.callStaticMethod(this._JSB_ANDROID_PATH, "getAdvertisingChannel", "()Ljava/lang/String;");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            str = this.callStaticMethod("CsjAdReward", "AdvertisingChannel", "");
        }
        return str;
    }

    /**
     * 复制到剪切板
     * @description Andorid功能 CocosToJava
     * @param str   剪切板字符串内容
     */
    public static setClipboard(str: string) {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "setClipboard", "(Ljava/lang/String;)V", str);
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {

        }
        else if (cc.sys.isBrowser) {
            var input = str;
            const el: any = document.createElement('textarea');
            el.value = input;
            el.setAttribute('readonly', '');
            el.style.contain = 'strict';
            el.style.position = 'absolute';
            el.style.left = '-9999px';
            el.style.fontSize = '12pt';

            const selection = getSelection();
            var originalRange: any = false;
            if (selection.rangeCount > 0) {
                originalRange = selection.getRangeAt(0);
            }
            document.body.appendChild(el);
            el.select();
            el.selectionStart = 0;
            el.selectionEnd = input.length;

            var success = false;
            try {
                success = document.execCommand('copy');
            } catch (err) { }

            document.body.removeChild(el);

            if (originalRange) {
                selection.removeAllRanges();
                selection.addRange(originalRange);
            }

            return success;
        }
    }

    /**
     * 请求用户授权  
     * @description Andorid功能 CocosToJava
     */
    public static requestPermission() {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "requestPermission", "()V");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            this.callStaticMethod("AppController", "requestPermission", "");
        }
    }

    /**
     * 获取安卓的版本号  
     * @description Andorid功能 CocosToJava
     */
    public static getAppVersion() {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "getAppVersion", "()V");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            this.callStaticMethod("AppController", "getAppVersion", "");
        }
    }

    /**
    * 设置安卓得版本号
    * @description Andorid功能 JavaToCocos
    * @param       appVersion app版本号
    */
    public static setAppVersion(appVersion: string) {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            // GameConst.appVersion = appVersion;
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {

        }
    }

    /**
     * 安装apk
     * @description   Andorid功能 CocosToJava
     * @param apkName apkName
     */
    public static installApk(apkName: string) {
        let fullPath = this.getWritablePath() + apkName;
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "installApk", "(Ljava/lang/String;)V", fullPath);
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            this.callStaticMethod("GameConfig", "installApk:", "");
        }
    }

    /** 
     * 是否可以启动游戏
     * @param packageName 包名
     * @param start       如存在是否启动
     * @returns ifCan         
     */
    static ifCanStartGame(packageName: string, start: boolean): boolean {
        let isCan = false;
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            isCan = this.callStaticMethod(this._JSB_ANDROID_PATH, "isStartGame", "(Ljava/lang/String;Z)Z", packageName, start);
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            isCan = this.callStaticMethod("GameConfig", "installApk:", "");
        }
        return isCan;
    }

    /**
     * 数数事件注册
     * @description 数数SDK功能 已经自动放到AS授权后了 前端无需调用
     * @returns 
     */
    static setTAEventRegister() {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "setTAEventRegister", "()V");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {

        }
    }

    /**
     * 发送自定义事件 自定义功能 CocosToJava
     * @description  发送统计事件
     * @param key    事件的key值
     * @param value  事件的value值
     */
    public static sendEvent(key: string, value: string) {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "sendEvent", "(Ljava/lang/String;Ljava/lang/String;)V", key, value);
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {

        }
    }

    /**
     * 微信授权
     * @description 微信SDK功能 CocosToJava
     */
    public static WxAuth() {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "WxAuth", "()V");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            this.callStaticMethod("AppController", "WxAuth", "");
        }
    }

    /**
     * 获取授权code
     * @description 微信SDK功能 JavaToCocos
     * @param code  微信code(Java返回)
     */
    public static onGetWxAccessCode(code) {
        // 暂时注释,需要网络通信
        gData.wechatData.code = code;
        console.log("=== gData.wechatData.code", gData.wechatData.code);
        gData.loginData.wxLogin();
    }

    /**
     * 微信打开小游戏
     * @description 微信SDK功能 CocosToJava
     */
    public static OpenMiniGame() {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "OpenMiniGame", "()V");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            this.callStaticMethod("AppController", "WxAuth", "");
        }
    }

    /**
     * 分享成微信小游戏
     * @description 微信SDK功能 CocosToJava
     */
    public static ShareToMiniGame() {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.callStaticMethod(this._JSB_ANDROID_PATH, "ShareToMiniGame", "()V");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            this.callStaticMethod("AppController", "WxAuth", "");
        }
    }

    /**
     * 分享图片
     * @description 微信SDK功能 CocosToJava
     */
    public static sharePic() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            return
        }
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            jsb.reflection.callStaticMethod(this._JSB_ANDROID_PATH, "sharePic", "()V");
        }
        else if (cc.sys.os == cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod("GameConfig", "sharePic:", "");
        }
    }

    /** 下载文件
     * @param url 下载地址
     * @param fileName 存储文件名称
     * @param successCb 成功回调
     * @param failCb 失败回调
     * @param progressCb 下载进度回调
     */
    public static downFile2Local(url, fileName, successCb, failCb, progressCb): any {
        var fullPath = jsb.fileUtils.getWritablePath() + fileName
        if (jsb) {
            var downloader = new jsb.Downloader();
            downloader.setOnFileTaskSuccess(function () {
                console.log("DownLoadM setOnFileTaskSuccess", "")
                if (successCb) {
                    console.log("DownLoadM result... ", jsb.fileUtils.isFileExist(fullPath))
                    console.log("DownLoadM setOnFileTaskSuccess fullPath...", fullPath)
                    successCb(fullPath);
                }
            });
            downloader.setOnTaskError(function (task: any, errorCode: number, errorCodeInternal: number, errorStr: string) {
                console.log("DownLoadM setOnTaskError", errorCode + " ; " + errorCodeInternal + " ; " + errorStr)
                if (failCb) {
                    failCb(fullPath);
                }
            });
            downloader.setOnTaskProgress(function (task: any, bytesReceived: number, totalBytesReceived: number, totalBytesExpected: number) {
                console.log("DownLoadM", bytesReceived + " ; " + totalBytesReceived + " ; " + totalBytesExpected)
                if (progressCb) {
                    progressCb(bytesReceived, totalBytesReceived, totalBytesExpected)
                }
            });
            downloader.createDownloadFileTask(url, fullPath);//创建下载任务
            return downloader
        }
    }
}

window['JsbMgr'] = JsbSystem
