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

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

const sortOrdering = (firstPost, secondPost) => {
  const dateOrdering =
    new Date(firstPost.publicationDate) < new Date(secondPost.publicationDate);

  if (firstPost.read && !secondPost.read) {
    return 1;
  } else if (secondPost.read && !firstPost.read) {
    return -1;
  }

  return dateOrdering;
};

const savedOrdering = (firstPost, secondPost) => {
  return new Date(firstPost.publicationDate) < new Date(secondPost.publicationDate);
};

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

  const filteredData = filteredPosts.map(post => ({ ...post, rule: { ...rule } }));

  return filteredData.sort(sortOrdering);
};

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

  const filteredData = filteredRules.map(rule => {
    const filteredPosts = posts.filter(post => {
      return post.rule === rule.id;
    });

    return filteredPosts.map(post => ({ ...post, rule: { ...rule } }));
  });

  const sortedPosts = [...filteredData.flat()].sort(sortOrdering);

  return sortedPosts;
};

export const filterPostsBySaved = (rules = [], posts = []) => {
  const filteredPosts = posts.filter(post => post.saved);
  return filteredPosts
    .map(post => ({ ...post, rule: { ...rules.find(rule => rule.id === post.rule) } }))
    .sort(savedOrdering);
};

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 [];
};
