'use strict';

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

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var tslib_es6 = require('../tslib.es6-0d92ef81.js');
var axios = require('axios');
var devops_token = require('./token.js');

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

var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);

function getDevopsTemplateList(_ref) {
  var projectId = _ref.projectId,
    host = _ref.host,
    secretInfo = _ref.secretInfo;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
    var accessToken, appCode, appSecret, devopsUid, resp;
    return _regeneratorRuntime__default["default"].wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 1;
          return devops_token.getDevopsAccessToken({
            secretInfo: secretInfo,
            host: host
          });
        case 1:
          accessToken = _context.sent;
          appCode = secretInfo.appCode, appSecret = secretInfo.appSecret, devopsUid = secretInfo.devopsUid;
          _context.next = 2;
          return axios__default["default"]({
            url: "".concat(host, "/prod/v4/apigw-app/projects/").concat(projectId, "/templates"),
            method: 'GET',
            headers: {
              'X-DEVOPS-UID': devopsUid,
              'Content-Type': 'application/json',
              'X-Bkapi-Authorization': JSON.stringify({
                bk_app_code: appCode,
                bk_app_secret: appSecret,
                access_token: accessToken
              })
            },
            params: {
              page: 1,
              pageSize: 90
            }
          })["catch"](function (err) {
            console.log('[getDevopsTemplateList ] err: ', err);
          });
        case 2:
          resp = _context.sent;
          return _context.abrupt("return", resp.data.data || {});
        case 3:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
function getDevopsTemplateLatestVersion(_ref2) {
  var projectId = _ref2.projectId,
    templateId = _ref2.templateId,
    host = _ref2.host,
    secretInfo = _ref2.secretInfo;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2() {
    var templateList, template;
    return _regeneratorRuntime__default["default"].wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 1;
          return getDevopsTemplateList({
            projectId: projectId,
            secretInfo: secretInfo,
            host: host
          });
        case 1:
          templateList = _context2.sent;
          template = templateList.models.find(function (item) {
            return item.templateId === templateId;
          });
          return _context2.abrupt("return", template === null || template === void 0 ? void 0 : template.version);
        case 2:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}
function getHeaderAndBaseUrl(_ref3) {
  var projectId = _ref3.projectId,
    templateId = _ref3.templateId,
    secretInfo = _ref3.secretInfo,
    host = _ref3.host;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3() {
    var appCode, appSecret, devopsUid, accessToken, url;
    return _regeneratorRuntime__default["default"].wrap(function (_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          appCode = secretInfo.appCode, appSecret = secretInfo.appSecret, devopsUid = secretInfo.devopsUid;
          _context3.next = 1;
          return devops_token.getDevopsAccessToken({
            secretInfo: secretInfo,
            host: host
          });
        case 1:
          accessToken = _context3.sent;
          url = "".concat(host, "/prod/v4/apigw-app/projects/").concat(projectId, "/templates/templateInstances?templateId=").concat(templateId);
          return _context3.abrupt("return", {
            headers: {
              'X-DEVOPS-UID': devopsUid,
              'Content-Type': 'application/json',
              'X-Bkapi-Authorization': JSON.stringify({
                bk_app_code: appCode,
                bk_app_secret: appSecret,
                access_token: accessToken
              })
            },
            baseUrl: url
          });
        case 2:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
}
function getDevopsTemplateInstances(_ref4) {
  var projectId = _ref4.projectId,
    templateId = _ref4.templateId,
    host = _ref4.host,
    secretInfo = _ref4.secretInfo,
    _ref4$page = _ref4.page,
    page = _ref4$page === void 0 ? 1 : _ref4$page,
    _ref4$pageSize = _ref4.pageSize,
    pageSize = _ref4$pageSize === void 0 ? 100 : _ref4$pageSize;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee4() {
    var _yield$getHeaderAndBa, headers, baseUrl, url, resp;
    return _regeneratorRuntime__default["default"].wrap(function (_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          _context4.next = 1;
          return getHeaderAndBaseUrl({
            projectId: projectId,
            templateId: templateId,
            secretInfo: secretInfo,
            host: host
          });
        case 1:
          _yield$getHeaderAndBa = _context4.sent;
          headers = _yield$getHeaderAndBa.headers;
          baseUrl = _yield$getHeaderAndBa.baseUrl;
          url = "".concat(baseUrl, "&page=").concat(page, "&pageSize=").concat(pageSize);
          _context4.next = 2;
          return axios__default["default"]({
            headers: headers,
            url: url,
            method: 'GET'
          })["catch"](function (err) {
            console.log('[getDevopsTemplateInstances] err: ', err);
          });
        case 2:
          resp = _context4.sent;
          return _context4.abrupt("return", resp.data);
        case 3:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  }));
}
function getAllDevopsTemplateInstances(reqParam) {
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee5() {
    var list;
    return _regeneratorRuntime__default["default"].wrap(function (_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          list = [];
          _context5.next = 1;
          return innerGetInstances(list, reqParam);
        case 1:
          return _context5.abrupt("return", list);
        case 2:
        case "end":
          return _context5.stop();
      }
    }, _callee5);
  }));
}
function innerGetInstances() {
  var allData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var reqParam = arguments.length > 1 ? arguments[1] : undefined;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee6() {
    var resp, _ref5, page, _ref5$instances, instances;
    return _regeneratorRuntime__default["default"].wrap(function (_context6) {
      while (1) switch (_context6.prev = _context6.next) {
        case 0:
          _context6.next = 1;
          return getDevopsTemplateInstances(reqParam);
        case 1:
          resp = _context6.sent;
          _ref5 = resp.data || {}, page = _ref5.page, _ref5$instances = _ref5.instances, instances = _ref5$instances === void 0 ? [] : _ref5$instances;
          allData.push.apply(allData, _toConsumableArray__default["default"](instances));
          if (instances.length) {
            _context6.next = 2;
            break;
          }
          return _context6.abrupt("return");
        case 2:
          _context6.next = 3;
          return innerGetInstances(allData, Object.assign(Object.assign({}, reqParam), {
            page: page + 1
          }));
        case 3:
        case "end":
          return _context6.stop();
      }
    }, _callee6);
  }));
}
function createDevopsTemplateInstances(_ref6) {
  var projectId = _ref6.projectId,
    templateId = _ref6.templateId,
    host = _ref6.host,
    pipelineName = _ref6.pipelineName,
    pipelineParam = _ref6.pipelineParam,
    secretInfo = _ref6.secretInfo,
    _ref6$useTemplateSett = _ref6.useTemplateSettings,
    useTemplateSettings = _ref6$useTemplateSett === void 0 ? true : _ref6$useTemplateSett;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee7() {
    var version, _yield$getHeaderAndBa2, headers, baseUrl, url, resp;
    return _regeneratorRuntime__default["default"].wrap(function (_context7) {
      while (1) switch (_context7.prev = _context7.next) {
        case 0:
          _context7.next = 1;
          return getDevopsTemplateLatestVersion({
            templateId: templateId,
            projectId: projectId,
            secretInfo: secretInfo,
            host: host
          });
        case 1:
          version = _context7.sent;
          console.log('[createDevopsTemplateInstances] version: ', version);
          _context7.next = 2;
          return getHeaderAndBaseUrl({
            projectId: projectId,
            templateId: templateId,
            secretInfo: secretInfo,
            host: host
          });
        case 2:
          _yield$getHeaderAndBa2 = _context7.sent;
          headers = _yield$getHeaderAndBa2.headers;
          baseUrl = _yield$getHeaderAndBa2.baseUrl;
          url = "".concat(baseUrl, "&version=").concat(version, "&useTemplateSettings=").concat(useTemplateSettings);
          _context7.next = 3;
          return axios__default["default"]({
            headers: headers,
            url: url,
            method: 'post',
            data: [{
              pipelineName: pipelineName,
              param: pipelineParam
            }]
          })["catch"](function (err) {
            console.log('[createDevopsTemplateInstances] err: ', err);
          });
        case 3:
          resp = _context7.sent;
          return _context7.abrupt("return", resp.data);
        case 4:
        case "end":
          return _context7.stop();
      }
    }, _callee7);
  }));
}
function updateDevopsTemplateInstances(_ref7) {
  var projectId = _ref7.projectId,
    templateId = _ref7.templateId,
    pipelineId = _ref7.pipelineId,
    host = _ref7.host,
    pipelineName = _ref7.pipelineName,
    pipelineParam = _ref7.pipelineParam,
    _ref7$useTemplateSett = _ref7.useTemplateSettings,
    useTemplateSettings = _ref7$useTemplateSett === void 0 ? true : _ref7$useTemplateSett,
    secretInfo = _ref7.secretInfo;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee8() {
    var version, _yield$getHeaderAndBa3, headers, baseUrl, url, resp;
    return _regeneratorRuntime__default["default"].wrap(function (_context8) {
      while (1) switch (_context8.prev = _context8.next) {
        case 0:
          _context8.next = 1;
          return getDevopsTemplateLatestVersion({
            templateId: templateId,
            projectId: projectId,
            secretInfo: secretInfo,
            host: host
          });
        case 1:
          version = _context8.sent;
          console.log('[updateDevopsTemplateInstances] version: ', version);
          _context8.next = 2;
          return getHeaderAndBaseUrl({
            projectId: projectId,
            templateId: templateId,
            secretInfo: secretInfo,
            host: host
          });
        case 2:
          _yield$getHeaderAndBa3 = _context8.sent;
          headers = _yield$getHeaderAndBa3.headers;
          baseUrl = _yield$getHeaderAndBa3.baseUrl;
          url = "".concat(baseUrl, "&version=").concat(version, "&useTemplateSettings=").concat(useTemplateSettings);
          _context8.next = 3;
          return axios__default["default"]({
            headers: headers,
            url: url,
            method: 'PUT',
            data: [{
              pipelineName: pipelineName,
              pipelineId: pipelineId,
              param: pipelineParam
            }]
          })["catch"](function (err) {
            console.log('[updateDevopsTemplateInstances] err: ', err);
          });
        case 3:
          resp = _context8.sent;
          return _context8.abrupt("return", resp.data);
        case 4:
        case "end":
          return _context8.stop();
      }
    }, _callee8);
  }));
}

exports.createDevopsTemplateInstances = createDevopsTemplateInstances;
exports.getAllDevopsTemplateInstances = getAllDevopsTemplateInstances;
exports.getDevopsTemplateInstances = getDevopsTemplateInstances;
exports.updateDevopsTemplateInstances = updateDevopsTemplateInstances;
