"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.buildQuestionList = exports.buildSuggestionList = exports.removeCommaSeparatedItem = exports.addCommaSeparatedItem = exports.withoutText = exports.textAppended = void 0;

var _question = require("./question");

const textAppended = (existing, newPhrase) => {
  if (!existing) {
    return newPhrase;
  }

  let cleaned = existing.trim();

  if (cleaned.slice(-1)[0] !== '.') {
    cleaned = cleaned + '.';
  }

  return "".concat(cleaned, " ").concat(newPhrase);
};

exports.textAppended = textAppended;

const withoutText = (existing = '', phraseToRemove) => existing.replace(phraseToRemove, '').replace('  ', ' ').trim();

exports.withoutText = withoutText;

const getAsArray = (existing = '') => existing.split(',').map(item => item.trim()).filter(Boolean);

const addCommaSeparatedItem = (existing, newItem) => [...getAsArray(existing), newItem].join(', ');

exports.addCommaSeparatedItem = addCommaSeparatedItem;

const removeCommaSeparatedItem = (existing, toRemove) => getAsArray(existing).filter(item => item !== toRemove).join(', ');

exports.removeCommaSeparatedItem = removeCommaSeparatedItem;

const buildSuggestionList = (matchingSuggestion, value, autoSuggestType) => matchingSuggestion && autoSuggestType ? matchingSuggestion.slice(0, 5).map(({
  phrase
}) => {
  let pressed;

  if (autoSuggestType === 'single') {
    pressed = value && value.trim() === phrase;
  } else {
    pressed = value && value.includes(phrase);
  }

  return {
    phrase,
    pressed
  };
}) : null;

exports.buildSuggestionList = buildSuggestionList;

const buildQuestionList = (config, data, suggestionsByField) => {
  const result = [];

  const addQuestion = item => {
    const {
      suggestions,
      deleting
    } = suggestionsByField[item.name] || {};
    let value = item.defaultValue;

    if (data.hasOwnProperty(item.name)) {
      value = data[item.name];
    }

    const question = Object.assign({}, (0, _question.decorateFormItem)(item, value, data), {
      value,
      suggestions: buildSuggestionList(suggestions, value, item.autoSuggestType),
      suggestionsDeleting: !!deleting
    });
    result.push(question);

    if (question.choices) {
      question.choices.forEach(({
        val,
        questions
      }) => {
        if (question.value === val && questions) {
          questions.forEach(addQuestion);
        }
      });
    }
  };

  config.forEach(addQuestion);
  return result;
};

exports.buildQuestionList = buildQuestionList;