import global from './global';
import baseUtil from '../utils/base';
import errUtil from '../utils/error';
import WebSocketManager from '../manager/webSocketManager';
import { callAPI } from './core/callManager';
import { sysLogger } from './logger';

const tryRequest = function (...params) {
  return callAPI(() => {
    const { network } = global.platform.adapter || {};

    // 未定义
    if (!network || !baseUtil.isFun(network.request)) {
      return undefined;
    }

    // 新方法
    return async (param) => {
      // 请求
      const resp = await network.request(param);
      const { statusCode, data } = resp || {};

      // code 转换
      if (statusCode) {
        resp.statusCode = parseInt(statusCode);
      }

      // dataType 为 json 时做数据转换
      const { dataType = 'json' } = param || {};
      switch (dataType) {
        case 'json':
          resp.data = baseUtil.toObject(data, null, true);
          break;
        case 'text':
          resp.data = baseUtil.toStr(data, '', true)
          break;
      }
      return resp
    }
  }, '', 'request', params)
}

const network = {
  /**
   * Http 网络请求
   * @param {Object} params
   */
  async request(params) {
    return tryRequest(params)
  },

  /**
   * websocket 实例
   */
  WebSocket: WebSocketManager
}

network.request = errUtil.catchErrStack(network.request, network, sysLogger)
export default network