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

export const fetchFileList = () => async dispatch => {
  try {
    const response = await client.query({
      query: gql`
        {
          files {
            id
            filename
            mimetype
            encoding
            path
            createdAt
            updatedAt
          }
        }
      `
    })

    dispatch({
      type: 'FILE-LIST',
      list: response.data.files
    })
  } catch (error) {
    console.error('file', error)
    dispatch({
      type: 'CLEAR-FILE-LIST'
    })
  }
}

/*
 ref. https://github.com/jaydenseric/graphql-multipart-request-spec#client
 - TODO support multiple file upload
 */
export const uploadFile = file => async dispatch => {
  try {
    let o = {
      query: `mutation ($file: Upload!) { 
        singleUpload(
          file: $file
        ) { id filename mimetype encoding path createdAt updatedAt } 
      }`,
      variables: {
        file: null
      }
    }

    let map = {
      '0': ['variables.file']
    }

    let fd = new FormData()
    fd.append('operations', JSON.stringify(o))
    fd.append('map', JSON.stringify(map))
    fd.append(0, file)

    fetch('/graphql', {
      method: 'POST',
      body: fd
    })
      .then(response => {
        response.json().then(data => {
          console.log('uploaded', data)
        })

        dispatch(fetchFileList())
      })
      .catch(e => {
        console.error(e)
      })
  } catch (e) {
    console.error(e)
  }
}
