import axios from 'axios';
import { makeActionCreator } from './actionCreator';
import {
  ARTICLES_API,
  GET_ARTICLE_LIST as getArticleListApi,
  COMMON_ARTICLE_API as getArticleApi,
  fetchGet,
  fetchPost,
  COMMON_ARTICLE_API as articleApi,
  fetchPut,
  fetchDelete,
  genFetchStatus,
  log
} from '../utils';

/**
 * TODO: 重用原fetchGet方法
 */
const fetchGetForArticles = dispatch => async (
  url,
  successAction,
  failedAction,
  articlesType,
  config = null
) => {
  try {
    const { data } = await axios.get(url, { ...config });
    if (data.errors) {
      dispatch(failedAction(data.errors));
    } else {
      dispatch(successAction(data, articlesType));
    }
  } catch (err) {
    dispatch(failedAction('Failed'));
    log(err);
  }
};

const fetching = makeActionCreator('FETCHING_ARTICLES');
const receiveArticles = makeActionCreator(
  'RECEIVE_ARTICLES',
  'response',
  'articlesType'
);
const fetchArticlesFailed = makeActionCreator(
  'FETCH_ARTICLES_FAILED',
  'message'
);

/**
 * TODO: 改变默认参数
 * @param {*} limit 
 * @param {*} offset 
 * @param {*} otherParams 包括tag favorited author
 */
export const fetchArticles = (
  limit = 10,
  offset = 0,
  articlesType,
  otherParams
) => dispatch => {
  dispatch(fetching());

  fetchGetForArticles(
    dispatch
  )(getArticleListApi, receiveArticles, fetchArticlesFailed, articlesType, {
    params: {
      limit,
      offset,
      ...otherParams
    }
  });
};

const { actions: articleActions } = genFetchStatus('article');

// 获取一篇文章
export const fetchArticle = slug => dispatch => {
  dispatch(articleActions[0]());

  return fetchGet(dispatch)(
    getArticleApi(slug),
    articleActions[1],
    articleActions[2]
  );
};

// update delete create
const { actions: commonArticleActions } = genFetchStatus('common_article');

// 写文章
export const createArticle = (
  token,
  title,
  description,
  body,
  tagList = []
) => dispatch => {
  dispatch(commonArticleActions[0]());

  return fetchPost(
    dispatch
  )(ARTICLES_API, commonArticleActions[1], commonArticleActions[2], {
    article: {
      title,
      description,
      body,
      tagList
    }
  });
};

export const updateMyArticle = (
  slug,
  title,
  description,
  body,
  tagList
) => dispatch => {
  dispatch(commonArticleActions[0]());
  return fetchPut(dispatch)(
    articleApi(slug),
    commonArticleActions[1],
    commonArticleActions[2],
    {
      article: {
        title,
        body,
        description,
        tagList
      }
    }
  );
};

export const deleteMyArticle = slug => dispatch => {
  dispatch(commonArticleActions[0]());
  return fetchDelete(dispatch)(
    articleApi(slug),
    commonArticleActions[1],
    commonArticleActions[2]
  );
};
