import { isEqual } from 'lodash';

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

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

import {
  RECEIVE_CATEGORY,
  RECEIVE_CATEGORIES,
  REQUEST_CATEGORY,
  REQUEST_CATEGORIES,
} from '../actions/categories.js';

import { MARK_POST_READ } from '../actions/posts.js';
import { MARK_SECTION_READ } from '../actions/selected.js';

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

export const categories = (state = { ...defaultState }, action) => {
  switch (action.type) {
    case RECEIVE_CATEGORY:
      return {
        ...state,
        items: {
          ...state.items,
          [action.category.id]: { ...action.category },
        },
        isFetching: false,
      };
    case RECEIVE_CATEGORIES:
      const receivedCategories = objectsFromArray(action.categories, 'id');

      return {
        ...state,
        items: { ...state.items, ...receivedCategories },
        isFetching: false,
      };
    case REQUEST_CATEGORIES:
    case REQUEST_CATEGORY:
      return { ...state, isFetching: true };
    case MARK_POST_READ:
      let postCategory = {};

      switch (action.section.type) {
        case CATEGORY_TYPE:
          postCategory = { ...state.items[action.section.id] };
          break;
        case RULE_TYPE:
          postCategory = { ...state.items[action.section.category] };
          break;
      }

      return {
        ...state,
        items: {
          ...state.items,
          [postCategory.id]: { ...postCategory, unread: postCategory.unread - 1 },
        },
      };
    case MARK_SECTION_READ:
      let sectionCategory = {};

      switch (action.section.type) {
        case CATEGORY_TYPE:
          sectionCategory = { ...state.items[action.section.id] };

          return {
            ...state,
            items: {
              ...state.items,
              [sectionCategory.id]: { ...sectionCategory, unread: 0 },
            },
          };
        case RULE_TYPE:
          sectionCategory = { ...state.items[action.section.category] };

          return {
            ...state,
            items: {
              ...state.items,
              [sectionCategory.id]: {
                ...sectionCategory,
                unread: sectionCategory.unread - action.section.unread,
              },
            },
          };
      }

      return state;
    default:
      return state;
  }
};
