import { isEqual } from 'lodash';

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

import {
  MARKING_POST,
  MARK_POST_READ,
  RECEIVE_POST,
  RECEIVE_POSTS,
  REQUEST_POSTS,
  TOGGLING_POST,
  TOGGLED_POST,
} from '../actions/posts.js';
import { SELECT_CATEGORY } from '../actions/categories.js';
import { SELECT_RULE } from '../actions/rules.js';
import { MARK_SECTION_READ } from '../actions/selected.js';

const defaultState = { items: {}, isFetching: false, isUpdating: false };

export const posts = (state = { ...defaultState }, action) => {
  switch (action.type) {
    case REQUEST_POSTS:
      return { ...state, isFetching: true };
    case RECEIVE_POST:
      return {
        ...state,
        items: { ...state.items, [action.post.id]: { ...action.post } },
      };
    case RECEIVE_POSTS:
      const receivedItems = objectsFromArray(action.posts, 'id');

      return {
        ...state,
        isFetching: false,
        items: { ...state.items, ...receivedItems },
      };
    case MARK_SECTION_READ:
      const updatedPosts = {};
      let relatedPosts = [];

      switch (action.section.type) {
        case CATEGORY_TYPE:
          relatedPosts = Object.values({ ...state.items }).filter(post => {
            return post.rule in { ...action.section.rules };
          });

          break;
        case RULE_TYPE:
          relatedPosts = Object.values({ ...state.items }).filter(post => {
            return post.rule === action.section.id;
          });

          break;
      }

      relatedPosts.forEach(post => {
        updatedPosts[post.id] = { ...post, read: true };
      });

      return {
        ...state,
        items: {
          ...state.items,
          ...updatedPosts,
        },
      };
    case MARKING_POST:
      return { ...state, isUpdating: true };
    case TOGGLING_POST:
      return { ...state, isUpdating: true };
    case MARK_POST_READ:
      return { ...state, isUpdating: false };
    case TOGGLED_POST:
      return { ...state, isUpdating: false };
    default:
      return state;
  }
};
