/* global Plotly:false */

const {ipcRenderer} = require('electron')
const hat = require('hat')

ipcRenderer.on('fig', (event, fig) => {
  const uid = hat()
  const gd = document.createElement('div')
  gd.id = uid
  document.body.appendChild(gd)

  Plotly.newPlot(gd, fig)
  .then(gd => Plotly.toImage(gd))
  .then(imgData => {

    ipcRenderer.send('img', {
      code: 200,
      imgData: imgData.replace(/^data:image\/\w+;base64,/, '')
    })

    Plotly.purge(gd)
    document.body.removeChild(gd)
  })
  .catch(err => {
    ipcRenderer.send('img', {
      code: 525,
      msg: JSON.stringify(err, ['message', 'arguments', 'type', 'name'])
    })
  })
})