'use strict';

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

var _regeneratorRuntime = require('@babel/runtime/regenerator');
var tslib_es6 = require('../tslib.es6-0d92ef81.js');
var nodejs_fs = require('../nodejs/fs.js');
var thirdParty_dotenv = require('../third-party/dotenv.js');
var rainbow_rainbowUser = require('./rainbow-user.js');
require('axios');
require('./helper/helper.js');
require('./sdk.js');
require('../json/json-parse.js');
require('../list/flat.js');

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

var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);

function writeEnvFromRainbow(_ref) {
  var envPath = _ref.envPath,
    rainbowAppId = _ref.rainbowAppId,
    rainbowUserId = _ref.rainbowUserId,
    rainbowSecretKey = _ref.rainbowSecretKey,
    rainbowKey = _ref.rainbowKey,
    envName = _ref.envName,
    groupName = _ref.groupName,
    sdk = _ref.sdk;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
    var appId, userId, secretKey, str;
    return _regeneratorRuntime__default["default"].wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          readLocalEnv(envPath);
          appId = rainbowAppId || process.env.RAINBOW_APP_ID || '';
          userId = rainbowUserId || process.env.RAINBOW_USER_ID || '';
          secretKey = rainbowSecretKey || process.env.RAINBOW_SECRET_KEY || '';
          if (appId) {
            _context.next = 1;
            break;
          }
          throw new Error('缺少 RAINBOW_APP_ID');
        case 1:
          _context.next = 2;
          return rainbow_rainbowUser.fetchRainbowConfig(rainbowKey, {
            appId: appId,
            envName: envName,
            groupName: groupName,
            userId: userId,
            secretKey: secretKey
          }, {
            sdk: sdk
          })["catch"](function (err) {
            console.log('[fetchRainbowConfig] err', err);
          });
        case 2:
          str = _context.sent;
          nodejs_fs.getFs().writeFileSync(envPath, str, {
            encoding: 'utf-8'
          });
          readLocalEnv(envPath);
          return _context.abrupt("return", true);
        case 3:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
function readLocalEnv(envPath) {
  thirdParty_dotenv.getDotenv().config({
    path: envPath
  });
}

exports.writeEnvFromRainbow = writeEnvFromRainbow;
