'use strict';

exports.__esModule = true;
exports.default = xhrAdapter;

function xhrAdapter(config) {
  var isProd = navigator.userAgent.includes('ks_prod');

  if (config._debug !== false && !isProd) {
    console.log("[request] " + config.headers.method, config);
  }

  return new Promise(function dispatchXhrRequest(resolve, reject) {
    // 超时定时器
    var timer = setTimeout(function (_) {
      var error = {
        message: "timeout of " + config.timeout + "ms exceeded"
      };
      error._config = config;
      reject(error);
    }, config.timeout);
    config.headers['appkey'] = config.headers.appkey && String(config.headers.appkey);
    ks.request(config.headers.method, JSON.parse(config.data), config.headers).then(function (res) {
      // 请求成功清除定时器
      clearTimeout(timer);

      if (config._debug !== false && !isProd) {
        console.log("[response] " + config.headers.method, res);
      }

      var responseData = res;
      var response = {
        data: responseData,
        status: 200,
        statusText: 'OK',
        headers: config.headers,
        config: config,
        request: config
      };
      resolve(response);
    }).catch(function (error) {
      clearTimeout(timer);

      if (config._debug !== false && !isProd) {
        console.log("[failed] " + config.headers.method, error);
      }

      error._config = config;
      reject(error);
    });
  });
}