import forEach from 'lodash/forEach';
import find from 'lodash/find';
import filter from 'lodash/filter';
import matches from 'lodash/matches';

export function applyFiltersToTags(filters, tags = []) {
  // We need to preserve order of tags that are in both new filter and old tags
  // as a result this requires a little bit more than just a basic map/reduce.
  const newTags = [];
  forEach(filters.symbols, (symbol) => {
    const tag = {type: 'symbol', value: symbol};
    newTags.push(tag);
    if (!find(tags, tag)) {
      tags.push(tag);
    }
  });
  forEach(filters.keywords, (keyword) => {
    const tag = {type: 'keyword', value: keyword};
    newTags.push(tag);
    if (!find(tags, tag)) {
      tags.push(tag);
    }
  });
  // Return original tags array with ones added/removed by filters
  return filter(tags, (tag) => find(newTags, tag));
}

export function applyTagsToFilters(tags, oldFilters) {
  // Unlike the previous function where tags are optional, this one REQUIRES filters
  const filters = Object.assign({}, oldFilters);
  filters.keywords = filter(tags, matches({type: 'keyword'})).map((v) => v.value);
  filters.symbols = filter(tags, matches({type: 'symbol'})).map((v) => v.value);
  return filters;
}
