import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../../tslib.es6-848120af.js';
import { saveJsonToLog } from '../../fs/fs-util.mjs';
import { queryGroupInfo } from '../../rainbow/rainbow-admin.mjs';
import { startDevopsPipeline } from '../pipeline.mjs';
import { updateDevopsTemplateInstances, createDevopsTemplateInstances } from '../template.mjs';
import { DEVOPS_MP_CI_CONFIG } from './config.mjs';
import { getUnusedPipelineList, getRainbowMpCIFileName, genOneFileFromRainbowGroup, compareFromLogFile, getPipelineName, isPipelineUpdated, parseRobotMap, getPipelineParam } from './helper.mjs';
import '../../fs/fs.mjs';
import '../../nodejs/crypto.mjs';
import '../../nodejs/fs.mjs';
import '../../nodejs/os.mjs';
import '../../nodejs/path.mjs';
import '../../time/time.mjs';
import '../../rainbow/helper/helper.mjs';
import '../../rainbow/helper/rainbow-base-request.mjs';
import 'axios';
import '../../rainbow/helper/rainbow-signature.mjs';
import '../token.mjs';
import '../../object/compare.mjs';
import '../../object/equal.mjs';

function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
var CI_PREFIX_MAP = DEVOPS_MP_CI_CONFIG.CI_PREFIX_MAP;
var usefulPipelineIdList = [];
function updateOrCreateInstance(_ref) {
  var rainbowMap = _ref.rainbowMap,
    mpCIKey = _ref.mpCIKey,
    isWxCI = _ref.isWxCI,
    forceUpdate = _ref.forceUpdate,
    devopsConfig = _ref.devopsConfig,
    templateIdMap = _ref.templateIdMap,
    onlyCollectNoUsedPipeline = _ref.onlyCollectNoUsedPipeline;
  var _a;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var newConfig, robotMapKey, newInfo, robotMap, _i, _Object$keys, robot, _robotMap$robot, branch, env, pipelineName, alreadyPipeline, cgiName, extraParam;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          newConfig = {};
          try {
            newConfig = JSON.parse(rainbowMap[mpCIKey].value);
          } catch (_b) {}
          robotMapKey = isWxCI ? 'robotMap' : 'qqRobotMap';
          newInfo = newConfig[robotMapKey] || {};
          robotMap = parseRobotMap(newInfo);
          _i = 0, _Object$keys = Object.keys(robotMap);
        case 1:
          if (!(_i < _Object$keys.length)) {
            _context.next = 7;
            break;
          }
          robot = _Object$keys[_i];
          _robotMap$robot = robotMap[robot], branch = _robotMap$robot.branch, env = _robotMap$robot.env;
          pipelineName = getPipelineName({
            robot: robot,
            env: env,
            branch: branch,
            ciKey: (_a = newConfig.ci) === null || _a === void 0 ? void 0 : _a.name,
            prefix: isWxCI ? CI_PREFIX_MAP.wx : CI_PREFIX_MAP.qq
          });
          console.log('[pipelineName]', pipelineName);
          _context.next = 2;
          return isPipelineUpdated({
            pipelineName: pipelineName,
            isWxCI: isWxCI,
            forceUpdate: forceUpdate,
            devopsConfig: devopsConfig,
            templateIdMap: templateIdMap
          });
        case 2:
          alreadyPipeline = _context.sent;
          console.log('[alreadyPipeline]', alreadyPipeline);
          cgiName = createDevopsTemplateInstances;
          extraParam = {};
          if (!(alreadyPipeline.type === 'CREATE')) {
            _context.next = 3;
            break;
          }
          _context.next = 5;
          break;
        case 3:
          if (!(alreadyPipeline.type === 'UPDATE')) {
            _context.next = 4;
            break;
          }
          cgiName = updateDevopsTemplateInstances;
          extraParam.pipelineId = alreadyPipeline.pipelineId;
          _context.next = 5;
          break;
        case 4:
          return _context.abrupt("continue", 6);
        case 5:
          if (extraParam.pipelineId) {
            usefulPipelineIdList.push(extraParam.pipelineId);
          }
          if (onlyCollectNoUsedPipeline) {
            _context.next = 6;
            break;
          }
          _context.next = 6;
          return realUpdateOrCreatePipeline({
            cgiName: cgiName,
            devopsConfig: devopsConfig,
            isWxCI: isWxCI,
            templateIdMap: templateIdMap,
            extraParam: extraParam,
            pipelineName: pipelineName,
            branch: branch,
            env: env,
            mpCIKey: mpCIKey,
            newConfig: newConfig,
            forceUpdate: forceUpdate
          });
        case 6:
          _i++;
          _context.next = 1;
          break;
        case 7:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
function realUpdateOrCreatePipeline(_ref2) {
  var cgiName = _ref2.cgiName,
    devopsConfig = _ref2.devopsConfig,
    isWxCI = _ref2.isWxCI,
    templateIdMap = _ref2.templateIdMap,
    extraParam = _ref2.extraParam,
    pipelineName = _ref2.pipelineName,
    branch = _ref2.branch,
    env = _ref2.env,
    mpCIKey = _ref2.mpCIKey,
    newConfig = _ref2.newConfig,
    forceUpdate = _ref2.forceUpdate;
  var _a, _b;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var res, pipelineId;
    return _regeneratorRuntime.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 1;
          return cgiName(Object.assign(Object.assign(Object.assign(Object.assign({}, devopsConfig), {
            templateId: isWxCI ? templateIdMap.WX_MP_CI : templateIdMap.QQ_MP_CI
          }), extraParam), {
            pipelineName: pipelineName,
            pipelineParam: _toConsumableArray(getPipelineParam({
              branch: branch,
              env: env,
              rainbowConfigKey: mpCIKey,
              repo: newConfig.ci.repo,
              isWxCI: isWxCI,
              devopsParams: newConfig.devopsParams || {}
            }))
          }))["catch"](function (err) {
            console.log('[cgiName] err', err);
          });
        case 1:
          res = _context2.sent;
          console.log('[cgiName] res', res);
          pipelineId = extraParam.pipelineId || ((_b = (_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.successPipelinesId) === null || _b === void 0 ? void 0 : _b[0]);
          if (!(!forceUpdate && pipelineId)) {
            _context2.next = 2;
            break;
          }
          _context2.next = 2;
          return startDevopsPipeline(Object.assign(Object.assign({}, devopsConfig), {
            pipelineId: pipelineId,
            data: {}
          }));
        case 2:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}
function handleChangedConfig(_ref3) {
  var _ref3$compareRes = _ref3.compareRes,
    compareRes = _ref3$compareRes === void 0 ? {} : _ref3$compareRes,
    forceUpdate = _ref3.forceUpdate;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
    var added, updated, deleted, rainbowMap, filterMpCI, updatedMpCIs;
    return _regeneratorRuntime.wrap(function (_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          added = compareRes.ADDED, updated = compareRes.UPDATED, deleted = compareRes.DELETED, rainbowMap = compareRes.newObj;
          filterMpCI = function filterMpCI(list) {
            return list.filter(function (item) {
              return item.endsWith('_mp_ci');
            });
          };
          console.log('[compareRes]', added, updated, deleted);
          updatedMpCIs = [];
          if (forceUpdate) {
            updatedMpCIs = filterMpCI(Object.keys(rainbowMap));
          } else {
            updatedMpCIs = [].concat(_toConsumableArray(filterMpCI(added)), _toConsumableArray(filterMpCI(updated)));
          }
          return _context3.abrupt("return", updatedMpCIs);
        case 1:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
}
function updateDevopsMpCIPipeline(_ref4) {
  var _ref4$isWxCI = _ref4.isWxCI,
    isWxCI = _ref4$isWxCI === void 0 ? true : _ref4$isWxCI,
    _ref4$forceUpdate = _ref4.forceUpdate,
    forceUpdate = _ref4$forceUpdate === void 0 ? false : _ref4$forceUpdate,
    _ref4$onlyCollectNoUs = _ref4.onlyCollectNoUsedPipeline,
    onlyCollectNoUsedPipeline = _ref4$onlyCollectNoUs === void 0 ? false : _ref4$onlyCollectNoUs,
    devopsConfig = _ref4.devopsConfig,
    templateIdMap = _ref4.templateIdMap,
    rainbowGroupSecretInfo = _ref4.rainbowGroupSecretInfo;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
    var resp, rainbowMap, compareRes, updatedMpCIs, _iterator, _step, mpCIKey, unusedPipeline, _t;
    return _regeneratorRuntime.wrap(function (_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          _context4.next = 1;
          return queryGroupInfo({
            secretInfo: rainbowGroupSecretInfo
          });
        case 1:
          resp = _context4.sent;
          rainbowMap = genOneFileFromRainbowGroup(resp);
          compareRes = compareFromLogFile(getRainbowMpCIFileName(isWxCI), rainbowMap);
          _context4.next = 2;
          return handleChangedConfig({
            compareRes: compareRes,
            forceUpdate: forceUpdate
          });
        case 2:
          updatedMpCIs = _context4.sent;
          _iterator = _createForOfIteratorHelper(updatedMpCIs);
          _context4.prev = 3;
          _iterator.s();
        case 4:
          if ((_step = _iterator.n()).done) {
            _context4.next = 6;
            break;
          }
          mpCIKey = _step.value;
          _context4.next = 5;
          return updateOrCreateInstance({
            rainbowMap: rainbowMap,
            mpCIKey: mpCIKey,
            isWxCI: isWxCI,
            forceUpdate: forceUpdate,
            devopsConfig: devopsConfig,
            templateIdMap: templateIdMap,
            onlyCollectNoUsedPipeline: onlyCollectNoUsedPipeline
          });
        case 5:
          _context4.next = 4;
          break;
        case 6:
          _context4.next = 8;
          break;
        case 7:
          _context4.prev = 7;
          _t = _context4["catch"](3);
          _iterator.e(_t);
        case 8:
          _context4.prev = 8;
          _iterator.f();
          return _context4.finish(8);
        case 9:
          unusedPipeline = getUnusedPipelineList({
            isWxCI: isWxCI,
            templateIdMap: templateIdMap,
            usefulList: usefulPipelineIdList
          });
          saveJsonToLog(rainbowMap, getRainbowMpCIFileName(isWxCI));
          saveJsonToLog({
            unusedPipeline: unusedPipeline
          }, "devops-unused-pipeline-".concat(isWxCI ? 'wx' : 'qq', ".json"));
        case 10:
        case "end":
          return _context4.stop();
      }
    }, _callee4, null, [[3, 7, 8, 9]]);
  }));
}

export { handleChangedConfig, updateDevopsMpCIPipeline };
