import { fetchBoardList, fetchBoard } from './actions-board'
import { fetchFileList } from './actions-file'
import { fetchFontList } from './actions-font'
import { fetchPublisherList } from './actions-publisher'
import { fetchDataSourceList } from './actions-datasource'

export const navigate = path => dispatch => {
  // Extract the page name from path.
  const page = path === '/' ? 'list-recent' : path.split('/')[1]
  const id = path.split('/')[2]

  dispatch({
    type: 'SET-PAGE-ID',
    route: { page, id }
  })

  // Any other info you might want to extract from the path (like page type),
  // you can do here
  dispatch(followRouteChange(page, id))
}

export const updateDrawerState = opened => dispatch => {
  dispatch({
    type: opened ? 'OPEN-DRAWER' : 'CLOSE-DRAWER'
  })
}

/* Route 변경시, 각 Route별로 필요한 state 설정 작업을 수행한다. */
export const followRouteChange = (page, id) => dispatch => {
  switch (page) {
    case 'list-by-group':
      dispatch({
        type: 'SET-CURRENT-GROUP',
        group: id,
        groupType: 'group'
      })

      dispatch(fetchBoardList('group', id))
      break

    case 'list-recent':
      dispatch({
        type: 'SET-CURRENT-GROUP',
        groupType: 'recent'
      })

      dispatch(fetchBoardList('recent'))
      break

    case 'list-by-playgroup':
      dispatch({
        type: 'SET-CURRENT-GROUP',
        group: id,
        groupType: 'playGroup'
      })

      dispatch(fetchBoardList('playGroup', id))
      break

    case 'modeler':
      dispatch(fetchBoard(id))
      break

    case 'player':
      dispatch({
        type: 'SET-CURRENT-GROUP',
        group: id
      })

      if (!id) {
        dispatch(setRoute('player'))
        return
      } else {
        dispatch(fetchBoardList('playGroup', id, 'player'))
      }
      break

    case 'viewer':
      dispatch(fetchBoard(id))
      break

    case 'setting-file':
      dispatch(fetchFileList())
      break

    case 'setting-font':
      dispatch(fetchFontList())
      break

    case 'setting-datasource':
      dispatch(fetchDataSourceList())
      break

    case 'setting-publisher':
      dispatch(fetchPublisherList())
      break

    case 'setting-security':
      break

    case 'signin':
    case 'signup':
    case 'user-profile':
      break

    default:
      page = 'page-404'
      break
  }

  dispatch({
    type: 'SET-PAGE-AND-ID',
    route: { page, id }
  })
}

export const setRoute = (page, id) => dispatch => {
  const location = window.location
  const origin = location.origin || location.protocol + '//' + location.host
  const path = id ? `/${page}/${id}` : `/${page}`
  const href = `${origin}${path}`

  if (location.pathname === path) return
  window.history.pushState({}, '', href)
  dispatch(navigate(path))
}
