'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 tgit_helper = require('./helper.js');
require('axios');

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);

// ---------------------------------------------------------------------------
// Group Detail & List
// ---------------------------------------------------------------------------
/**
 * 获取项目组的详细信息以及项目组下所有项目。
 *
 * 对应 API: `GET /api/v3/groups/:id`
 *
 * @see https://code.tencent.com/help/api/group#获取项目组的详细信息以及项目组下所有项目
 * @example
 *
 * fetchGroupDetail({
 *   groupId: 'pmd-mobile',
 *   privateToken: 'xxxxx',
 *   includeSubgroups: true,
 * }).then((detail) => {
 *   console.log(detail.projects);
 *   console.log(detail.sub_projects);
 * })
 */
function fetchGroupDetail(_ref) {
  var groupId = _ref.groupId,
    privateToken = _ref.privateToken,
    baseUrl = _ref.baseUrl,
    _ref$includeSubgroups = _ref.includeSubgroups,
    includeSubgroups = _ref$includeSubgroups === void 0 ? false : _ref$includeSubgroups;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
    var url;
    return _regeneratorRuntime__default["default"].wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          url = "/api/v3/groups/".concat(encodeURIComponent(String(groupId)));
          url = tgit_helper.resolveBaseUrl(baseUrl, url);
          return _context.abrupt("return", tgit_helper.instance({
            url: url,
            method: 'GET',
            params: {
              include_subgroups: includeSubgroups
            },
            headers: {
              'PRIVATE-TOKEN': privateToken
            }
          }).then(function (res) {
            return res.data;
          }));
        case 1:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
/**
 * 获取 / 搜索项目组列表。
 *
 * 对应 API: `GET /api/v3/groups`
 *
 * @see https://code.tencent.com/help/api/group#获取项目组列表
 * @example
 *
 * // 搜索名称包含 'pmd' 的项目组
 * fetchGroups({
 *   privateToken: 'xxxxx',
 *   search: 'pmd',
 *   page: 1,
 *   perPage: 20,
 * }).then((groups) => {
 *   console.log(groups.length);
 * })
 */
function fetchGroups(_ref2) {
  var privateToken = _ref2.privateToken,
    baseUrl = _ref2.baseUrl,
    search = _ref2.search,
    owned = _ref2.owned,
    minAccessLevel = _ref2.minAccessLevel,
    createdByMe = _ref2.createdByMe,
    excludeOrgGroup = _ref2.excludeOrgGroup,
    _ref2$page = _ref2.page,
    page = _ref2$page === void 0 ? 1 : _ref2$page,
    _ref2$perPage = _ref2.perPage,
    perPage = _ref2$perPage === void 0 ? 20 : _ref2$perPage;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2() {
    var url;
    return _regeneratorRuntime__default["default"].wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          url = '/api/v3/groups';
          url = tgit_helper.resolveBaseUrl(baseUrl, url);
          return _context2.abrupt("return", tgit_helper.instance({
            url: url,
            method: 'GET',
            params: {
              search: search,
              owned: owned,
              min_access_level: minAccessLevel,
              created_by_me: createdByMe,
              exclude_org_group: excludeOrgGroup,
              page: page,
              per_page: perPage
            },
            headers: {
              'PRIVATE-TOKEN': privateToken
            }
          }).then(function (res) {
            return res.data;
          }));
        case 1:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}
/**
 * 分页获取全部项目组列表（自动翻页）。
 *
 * 基于 {@link fetchGroups} 封装，自动遍历所有分页。
 * @example
 *
 * // 一次拿到当前 token 权限下的所有项目组
 * fetchAllGroups({
 *   privateToken: 'xxxxx',
 * }).then((groups) => {
 *   console.log(groups.length);
 * })
 */
function fetchAllGroups(_ref3) {
  var privateToken = _ref3.privateToken,
    baseUrl = _ref3.baseUrl,
    search = _ref3.search,
    owned = _ref3.owned,
    minAccessLevel = _ref3.minAccessLevel,
    createdByMe = _ref3.createdByMe,
    excludeOrgGroup = _ref3.excludeOrgGroup;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3() {
    var perPage, allGroups, page, groups;
    return _regeneratorRuntime__default["default"].wrap(function (_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          perPage = 100;
          allGroups = [];
          page = 1; // eslint-disable-next-line no-constant-condition
        case 1:
          _context3.next = 2;
          return fetchGroups({
            privateToken: privateToken,
            baseUrl: baseUrl,
            search: search,
            owned: owned,
            minAccessLevel: minAccessLevel,
            createdByMe: createdByMe,
            excludeOrgGroup: excludeOrgGroup,
            page: page,
            perPage: perPage
          });
        case 2:
          groups = _context3.sent;
          allGroups.push.apply(allGroups, _toConsumableArray__default["default"](groups));
          if (!(groups.length < perPage)) {
            _context3.next = 3;
            break;
          }
          return _context3.abrupt("continue", 4);
        case 3:
          page += 1;
          _context3.next = 1;
          break;
        case 4:
          return _context3.abrupt("return", allGroups);
        case 5:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
}
// ---------------------------------------------------------------------------
// Group Projects
// ---------------------------------------------------------------------------
/**
 * 获取某个组下所有项目（通过 `GET /api/v3/groups/:id` 接口，速度更快）。
 *
 * 当 `includeSubgroups` 为 true 时，会同时返回子组下的项目（`sub_projects`）。
 *
 * 兼容旧调用方式：返回值既是数组，又带有 `projects` 属性。
 * - 旧方式：`res.projects.map(item => ...)`
 * - 新方式：`res.map(item => ...)`
 * @example
 *
 * // 获取 pmd-mobile 组下（含子组）所有项目
 * fetchAllProjectsInGroup({
 *   groupName: 'pmd-mobile',
 *   privateToken: 'xxxxx',
 *   includeSubgroups: true,
 * }).then((res) => {
 *   res.forEach(p => console.log(p.path_with_namespace));
 * })
 */
function fetchAllProjectsInGroup(_ref4) {
  var groupName = _ref4.groupName,
    privateToken = _ref4.privateToken,
    baseUrl = _ref4.baseUrl,
    _ref4$includeSubgroup = _ref4.includeSubgroups,
    includeSubgroups = _ref4$includeSubgroup === void 0 ? true : _ref4$includeSubgroup;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee4() {
    var detail, allProjects, result;
    return _regeneratorRuntime__default["default"].wrap(function (_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          _context4.next = 1;
          return fetchGroupDetail({
            groupId: groupName,
            privateToken: privateToken,
            baseUrl: baseUrl,
            includeSubgroups: includeSubgroups
          });
        case 1:
          detail = _context4.sent;
          allProjects = [].concat(_toConsumableArray__default["default"](detail.projects || []), _toConsumableArray__default["default"](includeSubgroups ? detail.sub_projects || [] : [])); // 兼容旧调用方式 res.projects.map(...)
          result = allProjects;
          result.projects = allProjects;
          return _context4.abrupt("return", result);
        case 2:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  }));
}
/**
 * 递归获取某个组（含所有子组）下的全部仓库列表，支持多种过滤条件。
 *
 * 通过 `GET /api/v3/groups/:id`（`include_subgroups=true`）一次性获取
 * 组及子组下所有项目，避免逐页遍历 `/projects` 接口，速度更快。
 *
 * @param {object} options 输入配置
 * @param {string} options.groupName 组名称或完整路径，如 'pmd-mobile'
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] 自定义 API 基础路径，如 https://git.woa.com
 * @param {IGroupProjectFilter} [options.filter] 过滤配置
 * @returns {Promise<Array<IGroupProject>>} 过滤后的仓库列表
 * @example
 *
 * // 获取 pmd-mobile 组下所有仓库，排除 test 子组、归档仓库，以及前一天没有活跃的仓库
 * const yesterday = new Date();
 * yesterday.setDate(yesterday.getDate() - 1);
 *
 * const projects = await getGroupProjectsRecursive({
 *   groupName: 'pmd-mobile',
 *   privateToken: 'xxxxx',
 *   baseUrl: 'https://git.woa.com',
 *   filter: {
 *     excludePathPrefixes: ['pmd-mobile/test/'],
 *     excludeArchived: true,
 *     lastActivityAfter: yesterday,
 *     filterFn: (project) => !project.name.startsWith('deprecated-'),
 *   },
 * });
 *
 * console.log(projects);
 */
function getGroupProjectsRecursive(_ref5) {
  var groupName = _ref5.groupName,
    privateToken = _ref5.privateToken,
    baseUrl = _ref5.baseUrl,
    _ref5$filter = _ref5.filter,
    filter = _ref5$filter === void 0 ? {} : _ref5$filter;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee5() {
    var filterFn, _filter$excludePathPr, excludePathPrefixes, _filter$excludeArchiv, excludeArchived, lastActivityAfter, lastActivityThreshold, detail, allProjects;
    return _regeneratorRuntime__default["default"].wrap(function (_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          filterFn = filter.filterFn, _filter$excludePathPr = filter.excludePathPrefixes, excludePathPrefixes = _filter$excludePathPr === void 0 ? [] : _filter$excludePathPr, _filter$excludeArchiv = filter.excludeArchived, excludeArchived = _filter$excludeArchiv === void 0 ? true : _filter$excludeArchiv, lastActivityAfter = filter.lastActivityAfter;
          lastActivityThreshold = lastActivityAfter ? new Date(lastActivityAfter).getTime() : null; // 通过 /groups/:id 接口一次性获取组及子组下的项目
          _context5.next = 1;
          return fetchGroupDetail({
            groupId: groupName,
            privateToken: privateToken,
            baseUrl: baseUrl,
            includeSubgroups: true
          });
        case 1:
          detail = _context5.sent;
          allProjects = [].concat(_toConsumableArray__default["default"](detail.projects || []), _toConsumableArray__default["default"](detail.sub_projects || [])); // 应用过滤条件
          return _context5.abrupt("return", allProjects.filter(function (project) {
            // 过滤已归档
            if (excludeArchived && project.archived) {
              return false;
            }
            // 过滤路径前缀
            if (excludePathPrefixes.length > 0) {
              var matched = excludePathPrefixes.some(function (prefix) {
                return project.path_with_namespace.startsWith(prefix);
              });
              if (matched) {
                return false;
              }
            }
            // 过滤最后活跃时间
            if (lastActivityThreshold !== null && project.last_activity_at) {
              var projectTime = new Date(project.last_activity_at).getTime();
              if (projectTime < lastActivityThreshold) {
                return false;
              }
            }
            // 自定义过滤函数
            if (filterFn && !filterFn(project)) {
              return false;
            }
            return true;
          }));
        case 2:
        case "end":
          return _context5.stop();
      }
    }, _callee5);
  }));
}

exports.fetchAllGroups = fetchAllGroups;
exports.fetchAllProjectsInGroup = fetchAllProjectsInGroup;
exports.fetchGroupDetail = fetchGroupDetail;
exports.fetchGroups = fetchGroups;
exports.getGroupProjectsRecursive = getGroupProjectsRecursive;
