import { CATEGORY_TYPE, RULE_TYPE, SAVED_TYPE } from '../../constants.js';

const isEmpty = (object = {}) => {
  return Object.keys(object).length === 0;
};

export const filterPostsByRule = (rule = {}, posts = []) => {
  return posts.filter(post => {
    return post.rule.id === rule.id;
  });
};

export const filterPostsByCategory = (category = {}, rules = [], posts = []) => {
  const filteredRules = rules.filter(rule => {
    return rule.category === category.id;
  });

  const ruleIds = filteredRules.map(rule => rule.id);

  return [...posts].filter(post => ruleIds.includes(post.rule.id));
};

export const filterPostsBySaved = (rules = [], posts = []) => {
  return [...posts].filter(post => post.saved);
};

export const filterPosts = state => {
  const posts = Object.values({ ...state.posts.items });
  const rules = Object.values({ ...state.rules.items });

  switch (state.selected.item.type) {
    case CATEGORY_TYPE:
      return filterPostsByCategory({ ...state.selected.item }, rules, posts);
    case RULE_TYPE:
      return filterPostsByRule({ ...state.selected.item }, posts);
    case SAVED_TYPE:
      return filterPostsBySaved(rules, posts);
  }

  return [];
};
