import client from '../../app-shell/client'

import { setRoute } from './actions-route'
import { fetchBoardList } from './actions-board'

export const updateGroup = group => async dispatch => {
  try {
    const data = await client.updateGroup(group)

    dispatch(fetchGroupList())
  } catch (error) {
    console.error(error)
    /* TODO error */
  }
}

export const deleteGroup = group => async dispatch => {
  try {
    var { id } = group

    const data = await client.deleteGroup(id)

    dispatch(fetchGroupList())
  } catch (error) {
    console.error(error)
    /* TODO error */
  }
}
export const fetchGroupList = () => async dispatch => {
  try {
    const data = await client.fetchGroupList()

    dispatch({
      type: 'GROUP-LIST',
      list: data.groups
    })
  } catch (error) {
    dispatch({
      type: 'CLEAR-GROUP-LIST'
    })
  }
}

export const createGroup = group => async dispatch => {
  try {
    const data = await client.createGroup(group)

    dispatch(fetchGroupList())
    dispatch(fetchBoardList('group', data.createGroup.id))
  } catch (error) {
    console.error(error)
  }
}

export const joinGroup = (boardId, group) => async dispatch => {
  try {
    var { id } = group

    const data = await client.joinGroup(boardId, id)

    dispatch(setRoute('list-by-group', id))

    dispatch({
      type: 'BOARD-LIST',
      group: id,
      list: data.joinGroup.boards
    })
  } catch (error) {
    console.error(error)
    /* TODO error */
  }
}
