"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LaunchDarklyUtilsProjects = 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"));

// Class representing Projects functionality
var LaunchDarklyUtilsProjects = /*#__PURE__*/function () {
  /**
   * Projects specific api functions attached as 'LaunchDarklyUtils.projects'
   * @constructor LaunchDarklyUtilsProjects
   * @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 LaunchDarklyUtilsProjects(apiClient, log, ldUtils) {
    (0, _classCallCheck2["default"])(this, LaunchDarklyUtilsProjects);
    this.log = log;
    this.apiClient = apiClient;
    this.ldUtils = ldUtils;

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


  (0, _createClass2["default"])(LaunchDarklyUtilsProjects, [{
    key: "API_GROUP",
    get: function get() {
      return 'Projects';
    }
    /**
     * Get all projects in account
     * @returns {Promise}
     * @fulfil {Object} List of projects JSON
     * @reject {Error} object with message
     * @example ldutils getProjects
     */

  }, {
    key: "getProjects",
    value: function () {
      var _getProjects = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                return _context.abrupt("return", this.apiClient.apis[this.API_GROUP].getProjects().then(function (response) {
                  return response.body;
                })["catch"](function (e) {
                  throw {
                    api: 'getProjects',
                    message: e.message,
                    docs: 'https://apidocs.launchdarkly.com/reference#list-projects'
                  };
                }));

              case 1:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function getProjects() {
        return _getProjects.apply(this, arguments);
      }

      return getProjects;
    }()
    /**
     * get a single project by project key
     * @param projectKey - _id field of team member
     * @returns {Promise}
     * @fulfil {Object} project object json
     * @reject {Error} object with message
     * @example ldutils getProject new-project
     */

  }, {
    key: "getProject",
    value: function () {
      var _getProject = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(projectKey) {
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                return _context2.abrupt("return", this.apiClient.apis[this.API_GROUP].getProject({
                  projectKey: projectKey
                }).then(function (response) {
                  return response.body;
                })["catch"](function (e) {
                  throw {
                    api: 'getProject',
                    message: e.message,
                    docs: 'https://apidocs.launchdarkly.com/reference#get-project'
                  };
                }));

              case 1:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function getProject(_x) {
        return _getProject.apply(this, arguments);
      }

      return getProject;
    }()
    /**
     * Create a project in the account
     * @param {*} projectName - the name of the project
     * @param {*} projectKey - the key that identifies the project
     * @param {*} includeInSnippetByDefault - boolean true / false of whether should include a snippet
     * @param {*} tags - arrays of tags that can be associated with the project
     * @param {*} environments - an array of environments that are associated with the account
     * @param {*} defaultClientSideAvailability - An object that defines wether the SDK and / or mobile flags are available
     * @returns {Promise}
     * @fulfil {Object} project object json
     * @reject {Error} object with message
     * @example ldutils createProject new-project 'New Project' 'false' dev,Development,#41705:test,Test,f5a623 'true' 'false' marketing,online
     */

  }, {
    key: "createProject",
    value: function () {
      var _createProject = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(projectKey, projectName, includeInSnippetByDefault, environments, usingEnvironmentId, usingMobileKey, tags) {
        var includeInSnippetByDefaultBool, defaultClientSideAvailability, newProject;
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                if (typeof includeInSnippetByDefault !== 'undefined') {
                  if (includeInSnippetByDefault === 'true') {
                    includeInSnippetByDefaultBool = true;
                  } else {
                    includeInSnippetByDefaultBool = false;
                  }
                }

                if (typeof includeInSnippetByDefaultBool === 'undefined' && (typeof usingEnvironmentId != 'undefined' || typeof usingMobileKey != 'undefined')) {
                  if (typeof usingEnvironmentId === 'undefined' || usingEnvironmentId === 'true') {
                    usingEnvironmentId = true;
                  } else {
                    usingEnvironmentId = false;
                  }

                  if (typeof usingMobileKey === 'undefined' || usingMobileKey === 'true') {
                    usingMobileKey = true;
                  } else {
                    usingMobileKey = false;
                  }

                  defaultClientSideAvailability = {
                    usingEnvironmentId: usingEnvironmentId,
                    usingMobileKey: usingMobileKey
                  };
                }

                newProject = {
                  key: projectKey,
                  name: projectName,
                  includeInSnippetByDefault: includeInSnippetByDefaultBool,
                  tags: this.getTagsArray(tags),
                  environments: this.getEnvironmentsArray(environments),
                  defaultClientSideAvailability: defaultClientSideAvailability
                };
                return _context3.abrupt("return", this.apiClient.apis[this.API_GROUP].postProject({
                  projectBody: newProject
                }).then(function (response) {
                  return response.body;
                })["catch"](function (e) {
                  throw {
                    api: 'createProject',
                    message: e.message,
                    docs: 'https://apidocs.launchdarkly.com/reference#create-project'
                  };
                }));

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

      function createProject(_x2, _x3, _x4, _x5, _x6, _x7, _x8) {
        return _createProject.apply(this, arguments);
      }

      return createProject;
    }()
    /**
     * Patch a single project using jsonPatch notation
     * @param {*} projectKey - projectKey a key that identifies the project
     * @param {*} jsonPatch - an array of string using the JSON patch notation https://tools.ietf.org/html/rfc6902
     * @returns {Promise}
     * @fulfil {Object} an empty project
     * @reject {Error} object with message
     * @example ldutils updateProject new-project [{ op: 'replace', path: '/name', value: 'New project name' }]
     */

  }, {
    key: "updateProject",
    value: function () {
      var _updateProject = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(projectKey, jsonPatch) {
        return _regenerator["default"].wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                return _context4.abrupt("return", this.apiClient.apis[this.API_GROUP].patchProject({
                  projectKey: projectKey,
                  patchDelta: jsonPatch
                }).then(function (response) {
                  return response.body;
                })["catch"](function (e) {
                  throw {
                    api: 'patchProject',
                    message: e.message,
                    docs: 'https://apidocs.launchdarkly.com/reference#update-project'
                  };
                }));

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

      function updateProject(_x9, _x10) {
        return _updateProject.apply(this, arguments);
      }

      return updateProject;
    }()
    /**
     * Delete a project
     * @param {*} projectKey - projectKey a key that identifies the project
     * @fulfil {Object} an empty project
     * @reject {Error} object with message
     * @example ldutils deleteProject new-project
     */

  }, {
    key: "deleteProject",
    value: function () {
      var _deleteProject = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(projectKey) {
        return _regenerator["default"].wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                return _context5.abrupt("return", this.apiClient.apis[this.API_GROUP].deleteProject({
                  projectKey: projectKey
                }).then(function (response) {
                  return response.body;
                })["catch"](function (e) {
                  throw {
                    api: 'deleteProject',
                    message: e.message,
                    docs: 'https://apidocs.launchdarkly.com/reference#delete-project'
                  };
                }));

              case 1:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function deleteProject(_x11) {
        return _deleteProject.apply(this, arguments);
      }

      return deleteProject;
    }()
  }, {
    key: "getTagsArray",
    value: function getTagsArray(tags) {
      var tagsArray = [];

      if (tags) {
        if (tags.includes(',')) {
          tags.split(',').forEach(function (tag) {
            tagsArray.push(tag);
          });
        } else {
          // We have a single tag that needs to be added to the environment
          tagsArray.push(tags);
        }
      }

      return tagsArray;
    }
  }, {
    key: "getEnvironmentsArray",
    value: function getEnvironmentsArray(environments) {
      var _this = this;

      var environmentArray;

      if (environments) {
        environmentArray = [];

        if (environments.includes(':')) {
          environments.split(':').forEach(function (environment) {
            environmentArray.push(_this.getEnvironmentItem(environment));
          });
        } else {
          environmentArray.push(this.getEnvironmentItem(environments));
        }
      }

      return environmentArray;
    }
  }, {
    key: "getEnvironmentItem",
    value: function getEnvironmentItem(environment) {
      var environmentParts;

      if (environment) {
        environmentParts = environment.split(',');
      }

      if (!environment || environmentParts.length < 3) {
        throw 'Invalid environments configuration, should have 3 items, key, name and colour';
      }

      var environmentItem = {
        key: environmentParts[0],
        name: environmentParts[1],
        color: environmentParts[2]
      };
      return environmentItem;
    }
  }]);
  return LaunchDarklyUtilsProjects;
}();

exports.LaunchDarklyUtilsProjects = LaunchDarklyUtilsProjects;