"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LaunchDarklyUtilsMembers = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _lodash = _interopRequireDefault(require("lodash"));

// Class representing Team member functionality
var LaunchDarklyUtilsMembers = /*#__PURE__*/function () {
  /**
   * Team member specific api functions attached as 'LaunchDarklyUtils.members'
   * @constructor LaunchDarklyUtilsMembers
   * @param { Swagger } apiClient - generated launchdarkly apiClient
   * @param { Object } log - logger implementation, or 'console'
   * @param { LaunchDarklyUtils } ldUtils - primary utils class
   * @returns { LaunchDarklyUtilsMembers } team member api functions
   */
  function LaunchDarklyUtilsMembers(apiClient, log, ldUtils) {
    (0, _classCallCheck2["default"])(this, LaunchDarklyUtilsMembers);
    this.log = log;
    this.apiClient = apiClient;
    this.ldUtils = ldUtils;

    if (!this.ldUtils) {
      throw {
        message: 'LaunchDarklyUtilsRoles constructor requires ldUtils parameter'
      };
    }
  }
  /**
   * Api group object key in LD api
   * @returns {string}
   */


  (0, _createClass2["default"])(LaunchDarklyUtilsMembers, [{
    key: "API_GROUP",
    get: function get() {
      return 'Team members';
    }
    /**
     * Get all team members in account
     * @returns {Promise}
     * @param limit - max number of members to return (defaults to 20 per api)
     * @param offset - starting offset to return
     * @param filter - an optional filter https://apidocs.launchdarkly.com/reference#list-team-members
     * @fulfil {Object} team member list json
     * @reject {Error} object with message
     * @example ldutils getTeamMembers
     */

  }, {
    key: "getTeamMembers",
    value: function () {
      var _getTeamMembers = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(limit, offset, filter) {
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;
                return _context.abrupt("return", this.apiClient.apis[this.API_GROUP].getMembers({
                  limit: limit,
                  offset: offset,
                  filter: filter
                }).then(function (response) {
                  return response.body;
                }));

              case 4:
                _context.prev = 4;
                _context.t0 = _context["catch"](0);
                throw {
                  api: 'getMembers',
                  message: _context.t0.message,
                  docs: 'https://apidocs.launchdarkly.com/docs/list-team-members'
                };

              case 7:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this, [[0, 4]]);
      }));

      function getTeamMembers(_x, _x2, _x3) {
        return _getTeamMembers.apply(this, arguments);
      }

      return getTeamMembers;
    }()
    /**
     * get a single team member by id
     * @param memberId - _id field of team member
     * @returns {Promise}
     * @fulfil {Object} team member object json
     * @reject {Error} object with message
     * @example ldutils getTeamMember 5a3ad672761af020881a8814
     */

  }, {
    key: "getTeamMember",
    value: function () {
      var _getTeamMember = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(memberId) {
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.prev = 0;
                return _context2.abrupt("return", this.apiClient.apis[this.API_GROUP].getMember({
                  memberId: memberId
                }).then(function (response) {
                  return response.body;
                }));

              case 4:
                _context2.prev = 4;
                _context2.t0 = _context2["catch"](0);
                throw {
                  api: 'getMember',
                  message: _context2.t0.message,
                  docs: 'https://apidocs.launchdarkly.com/docs/get-team-member'
                };

              case 7:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this, [[0, 4]]);
      }));

      function getTeamMember(_x4) {
        return _getTeamMember.apply(this, arguments);
      }

      return getTeamMember;
    }()
    /**
     * Get a team member using a supplied email address
     * @param {string} emailAddress - email address of member to locate
     * @returns {Promise}
     * @fulfil {Object} team member json
     * @reject {Error} object with message
     * @example ldutils getTeamMemberByEmail owner-sample-account@launchdarkly.com
     */

  }, {
    key: "getTeamMemberByEmail",
    value: function () {
      var _getTeamMemberByEmail = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(emailAddress) {
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                return _context3.abrupt("return", this.getTeamMembers().then(function (memberList) {
                  var members = _lodash["default"].filter(memberList.items, {
                    email: emailAddress
                  });

                  if (members.length !== 1) {
                    throw {
                      api: 'getTeamMembers',
                      message: "member not found for email ".concat(emailAddress),
                      docs: 'https://apidocs.launchdarkly.com/docs/list-team-members'
                    };
                  }

                  return members[0];
                }));

              case 1:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function getTeamMemberByEmail(_x5) {
        return _getTeamMemberByEmail.apply(this, arguments);
      }

      return getTeamMemberByEmail;
    }()
    /**
     * Get a team member including customRoleKeys translated from customRoles array
     * @param {string} emailAddress - email address of member to locate
     * @returns {Promise}
     * @fulfil {Object} team member json
     * @reject {Error} object with message
     * @example ldutils getTeamMemberCustomRoles owner-sample-account@launchdarkly.com
     */

  }, {
    key: "getTeamMemberCustomRoles",
    value: function () {
      var _getTeamMemberCustomRoles = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(emailAddress) {
        var teamMember;
        return _regenerator["default"].wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return this.getTeamMemberByEmail(emailAddress);

              case 2:
                teamMember = _context4.sent;
                teamMember.customRoleKeys = [];
                return _context4.abrupt("return", this.ldUtils.roles.getCustomRoles().then(function (roles) {
                  teamMember.customRoles.forEach(function (memberRoleId) {
                    try {
                      teamMember.customRoleKeys.push(_lodash["default"].filter(roles.items, {
                        _id: memberRoleId
                      })[0]['key']);
                    } catch (e) {
                      throw {
                        api: 'getTeamMemberCustomRoles',
                        message: "role not found for _id ".concat(memberRoleId),
                        docs: 'https://apidocs.launchdarkly.com/docs/list-team-members'
                      };
                    }
                  });
                  return teamMember;
                }));

              case 5:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function getTeamMemberCustomRoles(_x6) {
        return _getTeamMemberCustomRoles.apply(this, arguments);
      }

      return getTeamMemberCustomRoles;
    }()
    /**
     * Invite a New Team Member by their Email Address
     * @param { String } emailAddress - Email Address of New Member
     * @param { String } initialRoleKey - Default Role for New Member
     * @returns {Promise}
     * @fulfil {Object} Team Member JSON
     * @reject {Error} object with message
     */

  }, {
    key: "inviteTeamMember",
    value: function () {
      var _inviteTeamMember = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(emailAddress) {
        var initialRoleKey,
            defaultRoles,
            user,
            members,
            _args5 = arguments;
        return _regenerator["default"].wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                initialRoleKey = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : 'reader';
                // Define var instead of inlining it for ease of reading later...
                defaultRoles = ['reader', 'writer', 'admin', 'owner'];
                user = {
                  email: emailAddress
                };
                members = {
                  membersBody: []
                }; // If Custom Role is Requested, the Key in the Member Object is different...

                !defaultRoles.includes(initialRoleKey) ? user.customRoles = [initialRoleKey] : user.role = initialRoleKey;
                members.membersBody.push(user);
                _context5.prev = 6;
                return _context5.abrupt("return", this.apiClient.apis[this.API_GROUP].postMembers(members).then(function (response) {
                  return response.body;
                }));

              case 10:
                _context5.prev = 10;
                _context5.t0 = _context5["catch"](6);
                throw {
                  api: 'postMembers',
                  message: _context5.t0.message,
                  docs: 'https://apidocs.launchdarkly.com/docs/create-team-members-1'
                };

              case 13:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this, [[6, 10]]);
      }));

      function inviteTeamMember(_x7) {
        return _inviteTeamMember.apply(this, arguments);
      }

      return inviteTeamMember;
    }()
  }]);
  return LaunchDarklyUtilsMembers;
}();

exports.LaunchDarklyUtilsMembers = LaunchDarklyUtilsMembers;