Source: app/actions/resources/recommendedReadingActions.js

import { createAction } from 'redux-actions';
import { GATEWAY_CONTENT_AUTH, GATEWAY_COMMUNITY_AUTH } from '../../data/Injectables';
import apiGetEntity from './apiActions/apiGetEntity';
import dedupeAsyncThunk from '../../util/dedupeAsyncThunk';
import apiGetCollection, { collectionCachingNoPagination } from './apiActions/apiGetCollection';
import { RECOMMENDED_READING_META_DATA } from '../../data/collectionIds';
import {
  RECOMMENDED_READING_SECTION,
  RECOMMENDED_READING_SECTION_META,
} from '../../data/entityTypes';
import { apiGet, apiPost } from './apiActions/apiRequest';

// TODO TAT-256 Replace 12-week-program endpoints with new recommended reading
// endpoints(must be done in the backend first)

export const GET_RECOMMENDED_READING_META_DATA =
  'recommendedReadingActions/GET_RECOMMENDED_READING_META_DATA';

export const getRecommendedReadingMetaData = dedupeAsyncThunk(
  (settings = { detailed: false, upToWeek: 12 }) =>
    apiGetCollection(
      GET_RECOMMENDED_READING_META_DATA,
      GATEWAY_CONTENT_AUTH,
      '/12-week-program',
      RECOMMENDED_READING_META_DATA,
      {},
      {
        requestData: {
          ...settings,
        },
        cache: collectionCachingNoPagination,
        entityType: RECOMMENDED_READING_SECTION_META,
      },
    ),
);

/**
 * Get the users current active section of the recommended reading plan
 */
export const GET_CURRENT_SECTION = 'recommendedReadingActions/GET_CURRENT_SECTION';
export const getCurrentSection = () => (dispatch, getState) => {
  const {
    recommendedReading: { section = null },
  } = getState();

  if (section === null) {
    return dispatch(
      apiGet(GET_CURRENT_SECTION, GATEWAY_COMMUNITY_AUTH, '/profiles/me/weeks/current'),
    );
  }

  return Promise.resolve({
    data: {
      index: section,
    },
  });
};

/**
 * Returns the content(articles / actions) for a given section depending on
 * section number that is passed in
 */
export const GET_SECTION_CONTENT = 'recommendedReadingActions/GET_SECTION_CONTENT';
export const getSectionContent = dedupeAsyncThunk(
  section => async (dispatch, getState) => {
    const {
      entities: { recommendedReadingSection },
    } = getState();

    const currentSection = recommendedReadingSection && recommendedReadingSection[section];

    if (currentSection === undefined) {
      dispatch(
        apiGetEntity(
          GET_SECTION_CONTENT,
          GATEWAY_CONTENT_AUTH,
          `/12-week-program/${section}`,
          RECOMMENDED_READING_SECTION,
          section,
          {
            section,
          },
        ),
      );
    }

    return Promise.resolve({
      data: {
        ...currentSection,
      },
    });
  },
  true,
);

/**
 * Get the users active section and then fetch the content for that section
 */
export const getCurrentSectionContent = () => dispatch =>
  dispatch(getCurrentSection())
    // Retrieve current week
    .then(result => dispatch(getSectionContent(Math.min(result.data.index, 12) || 0)));
// .catch(err => debug(`Error to request current week, ${err}`));

export const SET_SECTION = 'recommendedReadingActions/SET_SECTION';
export const setSection = createAction(SET_SECTION);

export const SET_SECTION_CONTENT = 'recommendedReadingActions/SET_SECTION_CONTENT';
export const setSectionContent = createAction(SET_SECTION_CONTENT);

/**
 * Update the users current active section and fetch data for that week
 */
export const SET_CURRENT_SECTION = 'recommendedReadingActions/SET_CURRENT_SECTION';
export const setCurrentSection = weekNumber => async dispatch =>
  await Promise.all([
    dispatch(setSection(Promise.resolve(weekNumber))),
    dispatch(getSectionContent(weekNumber)).then(result =>
      dispatch(setSectionContent(result.data)),
    ),
    dispatch(
      apiPost(SET_CURRENT_SECTION, GATEWAY_COMMUNITY_AUTH, '/profiles/me/weeks/start', {
        version: 'string',
        index: weekNumber,
      }),
    ),
  ]);