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

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

    dispatch({
      type: 'PUBLISHER-LIST',
      list: response.data.publishers
    })
  } catch (error) {
    console.error('publisher', error)
    dispatch({
      type: 'CLEAR-PUBLISHER-LIST'
    })
  }
}

export const createPublisher = publisher => async dispatch => {
  try {
    var { name, description, rule, type, datasrouce } = publisher

    const response = await client.mutate({
      mutation: gql`
        mutation CreatePublisher($publisher: NewPublisher!, $datasourceId: String!) {
          createPublisher(publisher: $publisher, datasourceId: $datasourceId) {
            id
            name
            description
            rule
            type
            createdAt
            updatedAt
          }
        }
      `,
      variables: {
        publisher: { name, description, rule, type },
        datasourceId: datasource
      }
    })

    const createdPublisher = response.data.createPublisher

    createdPublisher.rule = JSON.parse(createdPublisher.rule)

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

export const updatePublisher = publisher => async dispatch => {
  try {
    var { name, description, rule, type } = publisher

    const response = await client.mutate({
      mutation: gql`
        mutation UpdatePublisher($id: String!, $patch: PublisherPatch!) {
          updatePublisher(id: $id, publisher: $patch) {
            id
            name
            description
            rule
            type
            createdAt
            updatedAt
          }
        }
      `,
      variables: {
        id,
        patch: { name, description, rule, type }
      }
    })

    const updatedPublisher = response.data.updatePublisher

    updatedPublisher.rule = JSON.parse(updatedPublisher.rule)

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

export const deletePublisher = publisher => async dispatch => {
  try {
    var { id } = publisher

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

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