import { isEqual } from 'lodash';

import { objectsFromArray } from '../../../utils.js';

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

import {
  REQUEST_RULES,
  REQUEST_RULE,
  RECEIVE_RULES,
  RECEIVE_RULE,
} from '../actions/rules.js';
import { MARK_POST_READ } from '../actions/posts.js';
import { MARK_SECTION_READ } from '../actions/selected.js';

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

export const rules = (state = { ...defaultState }, action) => {
  switch (action.type) {
    case REQUEST_RULE:
    case REQUEST_RULES:
      return { ...state, isFetching: true };
    case RECEIVE_RULES:
      const receivedItems = objectsFromArray(action.rules, 'id');

      return {
        ...state,
        items: { ...state.items, ...receivedItems },
        isFetching: false,
      };
    case RECEIVE_RULE:
      return {
        ...state,
        items: { ...state.items, [action.rule.id]: { ...action.rule } },
        isFetching: false,
      };
    case MARK_POST_READ:
      const rule = { ...state.items[action.post.rule] };

      return {
        ...state,
        items: {
          ...state.items,
          [rule.id]: { ...rule, unread: rule.unread - 1 },
        },
      };
    case MARK_SECTION_READ:
      switch (action.section.type) {
        case RULE_TYPE:
          const rule = { ...state.items[action.section.id] };

          return {
            ...state,
            items: {
              ...state.items,
              [rule.id]: { ...rule, unread: 0 },
            },
          };
        case CATEGORY_TYPE:
          const updatedRules = {};
          const categoryRules = Object.values({ ...state.items }).filter(rule => {
            return rule.category === action.section.id;
          });

          categoryRules.forEach(rule => {
            updatedRules[rule.id] = { ...rule, unread: 0 };
          });

          return {
            ...state,
            items: {
              ...state.items,
              ...updatedRules,
            },
          };
      }

      return state;
    default:
      return state;
  }
};
