import 'isomorphic-fetch'

const LOGIN_REQUEST = 'LOGIN_REQUEST' // 获取开始
const LOGIN_RECEIVE = 'LOGIN_RECEIVE' // 获取成功
const LOGIN_FAILURE = 'LOGIN_FAILURE' // 获取失败

// 开始
const request = n => ({
  type: LOGIN_REQUEST,
  amount: n,
})

// 成功
const receive = (n, stories) => ({
  type: LOGIN_RECEIVE,
  amount: n,
  res: stories,
})

// 失败
const failure = (n, error) => ({
  type: LOGIN_FAILURE,
  amount: n,
  error,
})

// 获取 LOGIN 状态
export const login = n => (dispatch) => {
  dispatch(request(n))
  return fetch(
    '/api/user',
    {
      method: 'POST',
      mode: 'cors',
      headers: new Headers({
        'Content-Type': 'application/json',
        Accept: 'application/json',
      }),
      cache: 'default',
      body: JSON.stringify(n),
      credentials: 'include',
    },
  )
    .then((response) => {
      if (response.status > 200) {
        dispatch(failure(n, response.status))
      }
      return response.json()
    })
    .then(stories => dispatch(receive(n, stories)))
}

export default (state = {
  fetching: false,
  res: [],
  error: '',
}, action) => {
  switch (action.type) {
    case LOGIN_REQUEST:
      return {
        ...state,
        error: '',
        fetching: true,
      }
    case LOGIN_RECEIVE:
      return {
        ...state,
        fetching: false,
        res: action.res,
      }
    case LOGIN_FAILURE:
      return {
        ...state,
        fetching: false,
        error: action.error,
      }
    default:
      return state
  }
}
