import gql from 'graphql-tag'
import client from './fetch-client'

export const fetchDataSourceList = () => async dispatch => {
  try {
    const response = await client.query({
      query: gql`
        {
          datasources {
            id
            name
            description
            createdAt
            updatedAt
          }
        }
      `
    })

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

export const createDataSource = datasource => async dispatch => {
  try {
    var { name, description, credential, type } = datasource

    const response = await client.mutate({
      mutation: gql`
        mutation CreateDataSource($datasource: NewDataSource!) {
          createDataSource(datasource: $datasource) {
            id
            name
            description
            credential
            createdAt
            updatedAt
          }
        }
      `,
      variables: {
        datasource: { name, description, credential, type }
      }
    })

    const createdDataSource = response.data.createDataSource

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

export const updateDataSource = datasource => async dispatch => {
  try {
    var { name, description, credential, type } = datasource

    const response = await client.mutate({
      mutation: gql`
        mutation UpdateDataSource($id: String!, $datasource: DataSourcePatch!) {
          updateDataSource(id: $id, datasource: $datasource) {
            id
            name
            description
            credential
            createdAt
            updatedAt
          }
        }
      `,
      variables: {
        datasource: { name, description, credential, type }
      }
    })

    const updatedDataSource = response.data.updateDataSource

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

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

    const response = await client.mutate({
      mutation: gql`
        mutation($id: String!) {
          deleteDataSource(id: $id) {
            id
          }
        }
      `,
      variables: {
        id
      }
    })

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