/*
 *
 * CapFacebookPreview reducer
 *
 */

import { fromJS } from 'immutable';
import get from 'lodash/get';
import {
  GENERATE_PREVIEW_REQUEST,
  GENERATE_PREVIEW_SUCCESS,
  GENERATE_PREVIEW_FAILURE,
  CLEAR_PREVIEW,
  FETCH_PREVIEW_REQUESTED,
  FETCH_PREVIEW_SUCCESS,
  FETCH_PREVIEW_FAILURE,
  PREVIEW_NOT_REQUESTED,
} from './constants';

const initialState = fromJS({
  fetchPreviewStatus: PREVIEW_NOT_REQUESTED,
  previewIframe: "",
  previewIframeError: "",
});

function capFacebookPreviewReducer(state = initialState, action) {
  switch (action.type) {
    case GENERATE_PREVIEW_REQUEST:
      return state.set('fetchPreviewStatus', FETCH_PREVIEW_REQUESTED)
      .set('previewIframe', "")
      .set("previewIframeError", "");
    case GENERATE_PREVIEW_SUCCESS:
      return state.set('fetchPreviewStatus', FETCH_PREVIEW_SUCCESS)
      .set('previewIframe', get(action, 'payload.fbPreview[0].body', ""));
    case GENERATE_PREVIEW_FAILURE:
      return state.set('fetchPreviewStatus', FETCH_PREVIEW_FAILURE)
      .set('previewIframe', "")
      .set("previewIframeError", get(action, 'payload.message', ""));
    case CLEAR_PREVIEW:
      return state.set('fetchPreviewStatus', PREVIEW_NOT_REQUESTED)
      .set('previewIframe', "")
      .set("previewIframeError", "");
    default:
      return state;
  }
}

export default capFacebookPreviewReducer;
