import { isEqual } from 'lodash';

import { SELECT_CATEGORY } from '../actions/categories.js';
import { SELECT_RULE } from '../actions/rules.js';
import {
  RECEIVE_POST,
  RECEIVE_POSTS,
  SELECT_POST,
  UNSELECT_POST,
} from '../actions/posts.js';

import { MARK_SECTION_READ, SELECT_SAVED } from '../actions/selected.js';
import { MARK_POST_READ } from '../actions/posts.js';
import { SAVED_TYPE } from '../constants.js';

const defaultState = { item: {}, next: false, lastReached: false, post: {} };

export const selected = (state = { ...defaultState }, action) => {
  switch (action.type) {
    case SELECT_CATEGORY:
    case SELECT_RULE:
      if (state.item) {
        if (
          state.item.id === action.section.id &&
          state.item.type === action.section.type
        ) {
          if (state.item.clicks >= 2) {
            return {
              ...state,
              item: { ...action.section, clicks: 1 },
              next: false,
              lastReached: false,
            };
          }

          return {
            ...state,
            item: { ...action.section, clicks: state.item.clicks + 1 },
            next: false,
            lastReached: false,
          };
        }
      }

      return {
        ...state,
        item: { ...action.section, clicks: 1 },
        next: false,
        lastReached: false,
      };
    case SELECT_SAVED:
      return {
        ...state,
        item: { type: SAVED_TYPE },
        next: false,
        lastReached: false,
      };
    case RECEIVE_POSTS:
      return {
        ...state,
        next: action.next,
        lastReached: !action.next,
      };
    case RECEIVE_POST:
      const isCurrentPost = !isEqual(state.post, {}) && state.post.id === action.post.id;

      if (isCurrentPost) {
        return {
          ...state,
          post: { ...action.post },
        };
      }

      return {
        ...state,
      };
    case SELECT_POST:
      return { ...state, post: action.post };
    case UNSELECT_POST:
      return { ...state, post: {} };
    case MARK_POST_READ:
      return {
        ...state,
        item: { ...action.section, unread: action.section.unread - 1 },
      };
    case MARK_SECTION_READ:
      return {
        ...state,
        item: { ...action.section, clicks: 0, unread: 0 },
      };
    default:
      return state;
  }
};
