'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var isObj = _interopDefault(require('./isObj'));
var isFun = _interopDefault(require('./isFun'));
var isUdf = _interopDefault(require('./isUdf'));

/**
 * 先检测再调用jsb的方法，并返回一个Promise
 * @param {{
 *   inBiliApp: boolean;
 *   isSupport: (method: string) => Promise<boolean>;
 *   biliBridge: { callNative: options => any };
 * }} jsb js-bridge对象
 * @param {Object | (resolve, reject) => Object} optHandler
 *
 * @example
 * import * as jsb from '@bilibili/js-bridge';
 *
 * jsbCallNative(jsb, {
 *   method: 'ability.openScheme',
 *   data: { url: 'bilibili://schema/url' },
 * }).then(userInfo => {
 *   console.log(userInfo);
 * });
 *
 * jsbCallNative(jsb, resolve => ({
 *   method: 'auth.getUserInfo',
 *   data: { type: 'default', },
 *   callback: resolve,
 * })).then(userInfo => {
 *   console.log(userInfo);
 * });
 */
function jsbCallNative(jsb, optHandler) {
  return new Promise(function (resolve, reject) {
    var options = {};
    var support = null;

    if (isObj(optHandler)) {
      options = optHandler;
    } else if (isFun(optHandler)) {
      options = optHandler(resolve, reject);
    } else {
      return reject(new Error('参数格式不正确！'));
    }

    var _ref = jsb || {},
        inBiliApp = _ref.inBiliApp,
        isSupport = _ref.isSupport,
        biliBridge = _ref.biliBridge;

    if (isUdf(inBiliApp) || isUdf(isSupport) || isUdf(biliBridge)) {
      reject(new Error('JSB对象不正确！'));
    } else if (!inBiliApp) {
      resolve(null);
    } else {
      isSupport(options.method).then(function (isSpt) {
        support = isSpt;

        if (isSpt) {
          biliBridge.callNative(options);

          if (options.timeout && Object.keys(options).every(function (p) {
            return p !== 'callback' && !p.startsWith('on');
          })) {
            setTimeout(function () {
              return resolve();
            }, 500);
          }
        } else {
          reject(new Error('JSB方法不支持！'));
        }
      });
      setTimeout(function () {
        if (support === null) {
          reject(new Error('JSB方法不支持！'));
        }
      }, 1000);
    }
  }).then(function (res) {
    return isUdf(res) ? {} : res;
  });
}

module.exports = jsbCallNative;
