/**
 * Created by jair on 23/10/16.
 */
'use strict';
import dispatcher from '../dispatcher';
import { FEED_LOADED, COMMENT_POSTED, POST_CREATED } from '../constants/PostActionTypes';
import rest from '../util/rest-client';

export function loadFeed(userId, restricted) {
  if (userId) {

    let url = `/api/users/${userId}/posts`;

    if (!restricted) {
      url = `${url}/feed`;
    }

    rest().get(url)
      .then((response) => {
        dispatcher.dispatch({
          type: FEED_LOADED,
          posts: response.data
        });
      });
  }
}

export function commentPost(userId, postId, text) {
  rest().post(`/api/users/${userId}/posts/${postId}/comments`, {
    text
  }).then((response) => {
    dispatcher.dispatch({
      type: COMMENT_POSTED,
      postId,
      comment: response.data
    });
  });
}

export function createPost(userId, text, shares, attachments) {
  const users = shares.map((user) => {
    return user.id;
  });

  rest().post(`/api/users/${userId}/posts`, {
    text,
    users,
    attachments
  }).then((response) => {
    dispatcher.dispatch({
      type: POST_CREATED,
      post: response.data
    });
  })
}
