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

export const fetchFontList = () => async dispatch => {
  try {
    const response = await client.query({
      query: gql`
        {
          fonts {
            name
            provider
            uri
            path
            active
            createdAt
            updatedAt
          }
        }
      `
    })

    dispatch({
      type: 'FONT-LIST',
      list: response.data.fonts
    })
  } catch (error) {
    dispatch({
      type: 'CLEAR-FONT-LIST'
    })
  }
}

export const createFont = font => async dispatch => {
  try {
    var { name, provider, uri, path, active = false } = font

    const response = await client.mutate({
      mutation: gql`
        mutation CreateFont($font: NewFont!) {
          createFont(font: $font) {
            name
            provider
            uri
            path
            active
            createdAt
            updatedAt
          }
        }
      `,
      variables: {
        font: { name, provider, uri, path, active }
      }
    })

    const createdFont = response.data.createFont

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

export const updateFont = font => async dispatch => {
  try {
    var { name, provider, uri, path } = font

    const response = await client.mutate({
      mutation: gql`
        mutation UpdateFont($patch: FontPatch!) {
          updateFont(patch: $font) {
            name
            provider
            uri
            path
            active
            createdAt
            updatedAt
          }
        }
      `,
      variables: {
        font: { name, path }
      }
    })

    const updatedFont = response.data.updateFont

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

export const deleteFont = font => async dispatch => {
  try {
    var { name } = font

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

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