'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var axios = require('axios');
var rainbow_helper_helper = require('./helper/helper.js');
var rainbow_sdk = require('./sdk.js');
var list_flat = require('../list/flat.js');
require('../json/json-parse.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);

/**
 * 拉取七彩石配置
 * @param {String} key 七彩石的key
 * @param {object} secretInfo 密钥信息
 * @param {string} secretInfo.appId 项目Id
 * @param {string} secretInfo.envName 环境
 * @param {string} secretInfo.groupName 组名称
 * @returns {Promise<object>} 请求Promise
 *
 * @example
 *
 * fetchRainbowConfig('test', {
 *   appId: 'xx',
 *   envName: 'prod',
 *   groupName: 'robot',
 * }).then((resp) => {
 *   console.log(resp)
 * });
 *
 */
function fetchRainbowConfig(key, secretInfo, options) {
  var _a;
  var appID = secretInfo.appID,
    appId = secretInfo.appId,
    envName = secretInfo.envName,
    groupName = secretInfo.groupName,
    userId = secretInfo.userId,
    userID = secretInfo.userID,
    secretKey = secretInfo.secretKey;
  if ((userId || userID) && secretKey && (options === null || options === void 0 ? void 0 : options.sdk)) {
    return rainbow_sdk.fetchRainbowConfigFromSdk({
      secretInfo: secretInfo,
      sdk: options.sdk,
      key: key,
      initOptions: options === null || options === void 0 ? void 0 : options.initOptions,
      isFetchGroup: options === null || options === void 0 ? void 0 : options.isFetchGroup,
      tryJsonParse: (_a = options === null || options === void 0 ? void 0 : options.tryJsonParse) !== null && _a !== void 0 ? _a : false
    });
  }
  return new Promise(function (resolve, reject) {
    axios__default["default"]({
      url: "".concat(rainbow_helper_helper.BASE_URL, "/config.v2.ConfigService/PullConfigReq"),
      method: 'POST',
      data: {
        pull_item: {
          app_id: appId || appID,
          group: groupName,
          envName: envName
        }
      }
    }).then(function (res) {
      var _a;
      if (res.data.ret_code) {
        reject(res.data);
        return;
      }
      var keyValues = res.data.config.items[0].key_values;
      var flattenValues = list_flat.flatten(keyValues, 'key');
      var resData = (_a = flattenValues[key]) === null || _a === void 0 ? void 0 : _a.value;
      resolve(resData);
    })["catch"](function (err) {
      reject(err);
    });
  });
}

exports.fetchRainbowConfig = fetchRainbowConfig;
