"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Model = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _lodash = require("lodash");
var _function_form = require("./function_form");
/*
 * 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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const NO_NEXT_EXP = 'no next expression';
const MISSING_MODEL_ARGS = 'missing model args';
function getModelArgs(expressionType) {
  if (!expressionType) {
    return NO_NEXT_EXP;
  }
  if (!(expressionType !== null && expressionType !== void 0 && expressionType.modelArgs)) {
    return MISSING_MODEL_ARGS;
  }
  return (expressionType === null || expressionType === void 0 ? void 0 : expressionType.modelArgs.length) > 0 ? expressionType === null || expressionType === void 0 ? void 0 : expressionType.modelArgs : MISSING_MODEL_ARGS;
}
class Model extends _function_form.FunctionForm {
  constructor(props) {
    super(props);
    (0, _defineProperty2.default)(this, "requiresContext", void 0);
    const defaultProps = {
      requiresContext: true
    };
    const {
      requiresContext
    } = props;
    (0, _lodash.merge)(this, defaultProps, {
      requiresContext
    });
  }
  resolveArg(dataArg, props) {
    var _dataArg$arg, _modelArg$;
    // custom argument resolver
    // uses `modelArgs` from following expression to control which arguments get rendered
    const {
      nextExpressionType
    } = props;
    const modelArgs = getModelArgs(nextExpressionType);

    // if there is no following expression, or no modelArgs, argument is shown by default
    if (modelArgs === NO_NEXT_EXP || modelArgs === MISSING_MODEL_ARGS) {
      return {
        skipRender: false
      };
    }

    // if argument is missing from modelArgs, mark it as skipped
    const argName = dataArg === null || dataArg === void 0 ? void 0 : (_dataArg$arg = dataArg.arg) === null || _dataArg$arg === void 0 ? void 0 : _dataArg$arg.name;
    const modelArg = typeof modelArgs !== 'string' && modelArgs.find(arg => {
      if (Array.isArray(arg)) {
        return arg[0] === argName;
      }
      return arg === argName;
    });
    return {
      label: Array.isArray(modelArg) ? (_modelArg$ = modelArg[1]) === null || _modelArg$ === void 0 ? void 0 : _modelArg$.label : null,
      skipRender: !modelArg
    };
  }
}
exports.Model = Model;