function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/**
 * 
 * @file Metadata Queries API Helper
 * @author Box
 */
import find from 'lodash/find';
import getProp from 'lodash/get';
import includes from 'lodash/includes';
import API from '../../api';
import { ITEM_TYPE_FILE, JSON_PATCH_OP_REPLACE, JSON_PATCH_OP_TEST, METADATA_FIELD_TYPE_ENUM, METADATA_FIELD_TYPE_MULTISELECT } from '../../common/constants';
var SELECT_TYPES = [METADATA_FIELD_TYPE_ENUM, METADATA_FIELD_TYPE_MULTISELECT];

var MetadataQueryAPIHelper = function MetadataQueryAPIHelper(api) {
  var _this = this;

  _classCallCheck(this, MetadataQueryAPIHelper);

  _defineProperty(this, "createJSONPatchOperations", function (field, oldValue, newValue) {
    return [{
      op: JSON_PATCH_OP_TEST,
      path: "/".concat(field),
      value: oldValue
    }, {
      op: JSON_PATCH_OP_REPLACE,
      path: "/".concat(field),
      value: newValue
    }];
  });

  _defineProperty(this, "flattenMetadata", function (metadata) {
    var templateFields = getProp(_this.metadataTemplate, 'fields', []);
    var instance = getProp(metadata, "".concat(_this.templateScope, ".").concat(_this.templateKey));

    if (!instance) {
      return {};
    }

    var fields = Object.keys(instance).filter(function (key) {
      return !key.startsWith('$');
    }).map(function (key) {
      var templateField = find(templateFields, ['key', key]);
      var type = getProp(templateField, 'type'); // get data type

      var field = {
        name: key,
        value: instance[key],
        type: type
      };

      if (includes(SELECT_TYPES, type)) {
        // get "options" for enums or multiselects
        field.options = getProp(templateField, 'options');
      }

      return field;
    });
    return {
      enterprise: {
        fields: fields,
        id: instance.$id
      }
    };
  });

  _defineProperty(this, "flattenResponseEntry", function (_ref) {
    var item = _ref.item,
        metadata = _ref.metadata;
    var id = item.id,
        name = item.name,
        size = item.size;
    return {
      id: id,
      metadata: _this.flattenMetadata(metadata),
      name: name,
      size: size
    };
  });

  _defineProperty(this, "filterMetdataQueryResponse", function (response) {
    var _response$entries = response.entries,
        entries = _response$entries === void 0 ? [] : _response$entries,
        next_marker = response.next_marker;
    return {
      entries: entries.filter(function (entry) {
        return getProp(entry, 'item.type') === ITEM_TYPE_FILE;
      }),
      // return only file items
      next_marker: next_marker
    };
  });

  _defineProperty(this, "getFlattenedDataWithTypes", function (templateSchemaResponse) {
    _this.metadataTemplate = getProp(templateSchemaResponse, 'data');
    var _this$metadataQueryRe = _this.metadataQueryResponseData,
        entries = _this$metadataQueryRe.entries,
        next_marker = _this$metadataQueryRe.next_marker;
    return {
      items: entries.map(_this.flattenResponseEntry),
      nextMarker: next_marker
    };
  });

  _defineProperty(this, "getTemplateSchemaInfo", function (data) {
    var entries = data.entries;
    _this.metadataQueryResponseData = _this.filterMetdataQueryResponse(data);

    if (!entries || entries.length === 0) {
      // Don't make metadata API call to get template info
      return Promise.resolve();
    }

    var metadata = getProp(entries, '[0].metadata');
    _this.templateScope = Object.keys(metadata)[0];
    var instance = metadata[_this.templateScope];
    _this.templateKey = Object.keys(instance)[0];
    return _this.api.getMetadataAPI(true).getSchemaByTemplateKey(_this.templateKey);
  });

  _defineProperty(this, "queryMetadata", function (metadataQuery) {
    return new Promise(function (resolve, reject) {
      _this.api.getMetadataQueryAPI().queryMetadata(metadataQuery, resolve, reject, {
        forceFetch: true
      });
    });
  });

  _defineProperty(this, "fetchMetadataQueryResults", function (metadataQuery, successsCallback, errorCallback) {
    return _this.queryMetadata(metadataQuery).then(_this.getTemplateSchemaInfo).then(_this.getFlattenedDataWithTypes).then(successsCallback).catch(errorCallback);
  });

  _defineProperty(this, "updateMetadata", function (file, field, oldValue, newValue, successsCallback, errorCallback) {
    var operations = _this.createJSONPatchOperations(field, oldValue, newValue);

    return _this.api.getMetadataAPI(true).updateMetadata(file, _this.metadataTemplate, operations, successsCallback, errorCallback);
  });

  this.api = api;
};

export { MetadataQueryAPIHelper as default };
//# sourceMappingURL=MetadataQueryAPIHelper.js.map