import commonAPI from './common-api'
import bridgeAPI from './middle/web.js'

let sa = {};

let lib_plugin_track_timer = 0;
let js_uniapp_version = 'js_uniapp:0.0.6';


sa = bridgeAPI;
/*
做一次common-api的遍历
  如果bridgeAPI都实现了，就结束
  如果bridgeAPI没有实现，从instance中获取，如果还没有就=common-api
*/
Object.keys(commonAPI).forEach((key) => {
    if (!(key in bridgeAPI)) {
        if (typeof bridgeAPI.instance === 'object' && typeof bridgeAPI.instance[key] === 'function') {
            sa[key] = bridgeAPI.instance[key].bind(bridgeAPI.instance);
        } else {
            sa[key] = commonAPI[key].bind(commonAPI);
        }
    }
    // 如果是track，先加属性
    if (key === 'track') {
        let oldTrack = sa.track;
        sa.track = function () {
            let arr = [].slice.call(arguments, 0);
            if (++lib_plugin_track_timer === 1) {
                if (typeof arr[1] === 'object' && arr[1] !== null) {
                    arr[1]['$lib_plugin_version'] = [js_uniapp_version];
                } else {
                    arr[1] = {
                        $lib_plugin_version: [js_uniapp_version]
                    };
                }
            }
            return oldTrack.apply(sa, arr);
        };
    }
});




export default sa;
