"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ContentMagementWrapper = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _common = require("@kbn/kibana-utils-plugin/common");
var _errors = require("../common/errors");
var _content_management = require("../common/content_management");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

class ContentMagementWrapper {
  constructor(contentManagementClient) {
    (0, _defineProperty2.default)(this, "contentManagementClient", void 0);
    this.contentManagementClient = contentManagementClient;
  }
  async find(options) {
    const results = await this.contentManagementClient.search({
      contentTypeId: _content_management.DataViewSOType,
      query: {
        text: options.search,
        limit: options.perPage
      },
      options: {
        searchFields: options.searchFields,
        fields: options.fields
      }
    });
    return results.hits;
  }
  async get(id) {
    let response;
    try {
      response = await this.contentManagementClient.get({
        contentTypeId: _content_management.DataViewSOType,
        id
      });
    } catch (e) {
      var _e$body;
      if (((_e$body = e.body) === null || _e$body === void 0 ? void 0 : _e$body.statusCode) === 404) {
        throw new _common.SavedObjectNotFound('data view', id, 'management/kibana/dataViews');
      } else {
        throw e;
      }
    }
    if (response.meta.outcome === 'conflict') {
      throw new _errors.DataViewSavedObjectConflictError(id);
    }
    return response.item;
  }
  async update(id, attributes, options) {
    const response = await this.contentManagementClient.update({
      contentTypeId: _content_management.DataViewSOType,
      id,
      data: attributes,
      options
    });

    // cast is necessary since its the full object and not just the changes
    return response.item;
  }
  async create(attributes, options) {
    const result = await this.contentManagementClient.create({
      contentTypeId: _content_management.DataViewSOType,
      data: attributes,
      options
    });
    return result.item;
  }
  async delete(id) {
    await this.contentManagementClient.delete({
      contentTypeId: _content_management.DataViewSOType,
      id,
      options: {
        force: true
      }
    });
  }
}
exports.ContentMagementWrapper = ContentMagementWrapper;