/* eslint-disable func-names */
import fetch from 'isomorphic-fetch';
import _ from 'lodash';

import { getTerms, getTermId } from './utils';


export const REQUEST_ANNOTATIONS = 'REQUEST_ANNOTATIONS';
export function requestAnnotations(url) {
  return {
    type: REQUEST_ANNOTATIONS,
    url,
  };
}

export const RECEIVE_ANNOTATIONS = 'RECEIVE_ANNOTATIONS';
export function receiveAnnotations(url, annotations, terms) {
  return {
    type: RECEIVE_ANNOTATIONS,
    url,
    annotations,
    terms,
    receivedAt: Date.now(),
  };
}

export const RECEIVE_MESSAGES_COUNT = 'RECEIVE_MESSAGES_COUNT';
export function receiveMessagesCount(url, terms, terms64, messagesCount) {
  return {
    type: RECEIVE_MESSAGES_COUNT,
    terms,
    terms64,
    messagesCount,
  };
}

export const REQUEST_MESSAGES_COUNT = 'REQUEST_MESSAGES_COUNT';
export function requestMessagesCount(url, terms, terms64) {
  return {
    type: REQUEST_MESSAGES_COUNT,
    url,
    terms,
    terms64,
  };
}

export const FETCH_MESSAGES_COUNT = 'FETCH_MESSAGES_COUNT';
export function fetchMessagesCount(terms, discussionUrl, dashboardId) {
  const url = `${discussionUrl}count`;
  const terms64 = _.map(terms, term => getTermId(term, dashboardId));

  return function (dispatch) {
    dispatch(requestMessagesCount(url, terms, terms64));

    if (!discussionUrl) {
      return dispatch(receiveMessagesCount(url, terms, terms64, {}));
    }

    return fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(terms64),
    })
      .then(
        response => response.json(),
        error => console.log('An error occured.', error), // eslint-disable-line no-console
      )
      .then(
        json => dispatch(receiveMessagesCount(url, terms, terms64, json)),
      );
  };
}

export const FETCH_ANNOTATIONS = 'FETCH_ANNOTATIONS';
export function fetchAnnotations(url, discussionUrl, dashboardId) {
  return function (dispatch) {
    dispatch(requestAnnotations(url));

    return fetch(url)
      .then(
        response => response.json(),
        error => console.log('An error occured.', error), // eslint-disable-line no-console
      )
      .then((json) => {
        const annotations = json.rows;
        const terms = getTerms(annotations);

        dispatch(fetchMessagesCount(Object.keys(terms), discussionUrl, dashboardId));
        dispatch(receiveAnnotations(url, annotations, terms));
      });
  };
}
