import client from '../../app-shell/client'

export const fetchPublisherList = () => async dispatch => {
  try {
    const data = await client.fetchPublisherList()

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

export const createPublisher = publisher => async dispatch => {
  try {
    const data = await client.createPublisher(publisher)

    const createdPublisher = data.createPublisher

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

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

export const updatePublisher = publisher => async dispatch => {
  try {
    const data = await client.updatePublisher(publisher)

    const updatedPublisher = 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 data = await client.deletePublisher(id)

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