"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ListComponent = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _shared_component = require("./shared_component");
/*
 * 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.
 */

/** A component that suggests one of the give options, but accepts anything */
class ListComponent extends _shared_component.SharedComponent {
  constructor(name, list, parent, multiValued, allowNonValidValues) {
    super(name, parent);
    this.listGenerator = Array.isArray(list) ? function () {
      return list;
    } : list;
    this.multiValued = _lodash.default.isUndefined(multiValued) ? true : multiValued;
    this.allowNonValidValues = _lodash.default.isUndefined(allowNonValidValues) ? false : allowNonValidValues;
  }
  getTerms(context, editor) {
    if (!this.multiValued && context.otherTokenValues) {
      // already have a value -> no suggestions
      return [];
    }
    let alreadySet = context.otherTokenValues || [];
    if (_lodash.default.isString(alreadySet)) {
      alreadySet = [alreadySet];
    }
    let ret = _lodash.default.difference(this.listGenerator(context, editor), alreadySet);
    if (this.getDefaultTermMeta()) {
      const meta = this.getDefaultTermMeta();
      ret = _lodash.default.map(ret, function (term) {
        if (_lodash.default.isString(term)) {
          term = {
            name: term
          };
        }
        return _lodash.default.defaults(term, {
          meta: meta
        });
      });
    }
    return ret;
  }
  validateTokens(tokens) {
    if (!this.multiValued && tokens.length > 1) {
      return false;
    }

    // verify we have all tokens
    const list = this.listGenerator();
    const notFound = _lodash.default.some(tokens, function (token) {
      return list.indexOf(token) === -1;
    });
    if (notFound) {
      return false;
    }
    return true;
  }
  getContextKey() {
    return this.name;
  }
  getDefaultTermMeta() {
    return this.name;
  }
  match(token, context, editor) {
    if (!Array.isArray(token)) {
      token = [token];
    }
    if (!this.allowNonValidValues && !this.validateTokens(token, context, editor)) {
      return null;
    }
    const result = super.match(token, context, editor);
    result.context_values = result.context_values || {};
    result.context_values[this.getContextKey()] = token;
    return result;
  }
}
exports.ListComponent = ListComponent;