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

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

    dispatch({
      type: 'DATASOURCE-LIST',
      list: data.datasources
    })
  } catch (error) {
    console.error(error)
    dispatch({
      type: 'CLEAR-DATASOURCE-LIST'
    })
  }
}

export const createDataSource = datasource => async dispatch => {
  try {
    const data = await client.createDataSource(datasource)

    const createdDataSource = data.createDataSource

    dispatch(fetchDataSourceList())
  } catch (error) {
    console.error(error)
  }
}

export const updateDataSource = datasource => async dispatch => {
  try {
    const data = await client.updateDataSource(datasource)

    const updatedDataSource = data.updateDataSource

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

export const deleteDataSource = datasource => async dispatch => {
  try {
    var { id } = datasource

    const data = await client.deleteDataSource(id)

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