/**
 * 基础接口
 */
/* globals GLOBAL_OBJECT */
import { callNative, callNativeSync, getUid, emptyFn, throwError } from './util';
import * as eventHandlers from './util/eventHandlers';
import parseQuery from '../lib/parse-query';
import canIUseSupport from "../lib/canIUseSupport";
import system from "./system";
import { compareVersion } from "./util/commonFn";


function handleCallback(handler, callback) {
    if (eventHandlers.updateManagerHandlers[handler + 'Param']) {
        callback(eventHandlers.updateManagerHandlers[handler + 'Param']);
    } else {
        eventHandlers.updateManagerHandlers[handler + 'Callbacks'].push(callback);
    }
}
const updateManager = {
    applyUpdate() {
        const res = callNativeSync('updater.applyUpdate');

        if (res.code !== 0) {
            throwError(res.msg);
        }
    },
    onCheckForUpdate(callback = () => {}) {
        handleCallback('onCheckForUpdate', callback);
    },
    onUpdateFailed(callback = () => {}) {
        handleCallback('onUpdateFailed', callback);
    },
    onUpdateReady(callback = () => {}) {
        handleCallback('onUpdateReady', callback);
    }
};

export default {
    // 环境常量
    env: {
        USER_DATA_PATH: 'blfile://usr',
        SHARE_DATA_PATH: 'blfile://share'
    },
    /**
     * 判断小程序的API，回调，参数，组件等是否在当前版本可用。
     * @param {String} schema 成功回调
     */
    canIUse(schema) {
        if (typeof schema !== 'string') {
            // 判断类型
            throwError('canIUse:fail schema should be string');
        }

        // feature 支持canIUse修复
        const systemInfo = system.getSystemInfoSync()
        let supportResult = canIUseSupport.isSupport(schema, systemInfo.SDKVersion, systemInfo.platform)
        if (!supportResult.isThrough) {
            return supportResult.result
        }

        const result = callNativeSync('canIUse', { schema });

        return result.data.data;
    },
    /**
     * 获取小程序启动时的参数。与 App.onLaunch 的回调参数一致。
     *
     * @param {Object} [options = {}]
     * @param {Function} options.success 接口调用成功的回调函数
     * @param {Function} options.fail 接口调用失败的回调函数
     */
    getLaunchOptions(options = {}) {
        const callbackId = getUid();
        const successFn = typeof options.success === 'function' ? options.success : emptyFn;
        const failFn = typeof options.fail === 'function' ? options.fail : emptyFn;
        const completeFn = typeof options.complete === 'function' ? options.complete : emptyFn;

        const callbackFn = (result) => {
            if (result.code === 0) {
                const res = result.data.options || result.data;
                res.query = parseQuery('?' + res.query);
                successFn(Object.assign({ errMsg: 'getLaunchOptions:ok' }, res));
                completeFn(Object.assign({ errMsg: 'getLaunchOptions:ok' }, res));
            } else {
                failFn({ errMsg: result.msg });
                completeFn({ errMsg: result.msg });
            }
        };

        GLOBAL_OBJECT.callbacks[callbackId] = callbackFn;
        GLOBAL_OBJECT.callNative('getLaunchOptions', JSON.stringify(options), callbackId);
    },
    /**
     * 获取小程序启动时的参数。与 App.onLaunch 的回调参数一致。
     */
    getLaunchOptionsSync() {
        const result = callNativeSync('getLaunchOptionsSync').data;
        const res = result.options || result;
        res.query = parseQuery('?' + res.query);
        return res;
    },
    /**
     * 等同App.onError
     */
    onError(callback) {
        eventHandlers.onErrorHandlers.push(callback);
    },
    getUpdateManager() {
        return updateManager;
    },
    reLaunch(options = {}) {
        callNative('reLaunchApplet', options, {
            url: 'String'
        });
    },
    /*
    * 提示用户手动升级 APP 版本。
    *   author： 转山
    *   date:    2020/12/11
    * */
    updateApp(options = {}) {
        callNative('updateApp', options);
    },
    /*
    * 获取本次小程序启动时的参数。如果当前是冷启动，则返回值与 App.onLaunch的回调参数一致；如果当前是热启动，则返回值与 App.onShow 一致。
    *   author： 转山
    *   date:    2020/12/11
    * */
    getEnterOptionsSync() {
        let temp = global.__smallApp.enterOptions;
        return {
            path: temp.path,
            query: temp.query,
            referrerInfo: temp.referrerInfo,
            virtualId: temp.virtualId,
            envVersion: temp.envVersion
        };
    },
    // 判断是否支持canvas2期方案
    isCanvasSupportedSync(){
        const _sys = bl.getSystemInfoSync();
        let _isSupport = false;
        // 大于SDKVersion = 3.58.0
        if (compareVersion(_sys.SDKVersion, '3.58.0') >= 0) {
            if (_sys.platform.toLowerCase() === 'android') {
                if (_sys.innerSDKVersion && _sys.innerSDKVersion.length > 2 && compareVersion(_sys.innerSDKVersion, '3.58.0')>= 0) {
                    if (!global.document) _isSupport = true;
                }
            } else {
                _isSupport = true
            }
        }
        return _isSupport
    }
};
