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

export const fetchSettingList = query => async dispatch => {
  try {
    const response = await client.query({
      query: gql`
        {
          settings {
            name
            value
            createdAt
            updatedAt
          }
        }
      `
    })

    dispatch({
      type: 'REFRESH-SETTINGS',
      list: response.data.settings
    })
  } catch (error) {
    console.error(error)
    // dispatch({
    //   type: 'CLEAR-BOARD-LIST'
    // });
  }
}

export const createSetting = setting => async dispatch => {
  try {
    var { name, value } = setting

    const response = await client.mutate({
      mutation: gql`
        mutation CreateSetting($setting: NewSetting!) {
          createSetting(setting: $setting) {
            name
            value
            createdAt
            updatedAt
          }
        }
      `,
      variables: {
        setting: { name, value }
      }
    })

    const createdSetting = response.data.createSetting

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

export const updateSetting = setting => async dispatch => {
  try {
    var { name, value } = setting

    const response = await client.query({
      qery: gql`
        mutation UpdateSetting($patch: SettingPatch!) {
          updateSetting(patch: $patch) {
            name
            value
            createdAt
            updatedAt
          }
        }
      `,
      variables: {
        patch: { name, value }
      }
    })

    const updatedSetting = response.data.updateSetting

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

export const deleteSetting = setting => async dispatch => {
  try {
    var { name } = setting

    const response = await client.query({
      qery: gql`
        mutation($name: String!) {
          deleteSetting(name: $name) {
            name
          }
        }
      `,
      variables: {
        name
      }
    })

    const deletedSetting = response.data.deleteSetting

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