// https://forum.vuejs.org/t/how-to-use-helper-functions-for-imported-modules-in-vuejs-vue-template/6266/5
export default {
  methods: {
    deg2rad (deg) {
      return deg * (Math.PI / 180)
    },
    createLabelCanvas (text, fontsize, sizefactore, txtcolor) {
      // console.log('createLabelCanvas', this.data.Titre)
      const size = fontsize
      const borderSize = 5
      let lines = text.split('\n')
      const ctx = document.createElement('canvas').getContext('2d')
      const font = `${size}px bold noto_sans,sans-serif`
      ctx.font = font
      // measure how long the name will be
      const doubleBorderSize = borderSize * 2
      let width = 0
      for (var i = 0; i < lines.length; i++) {
        width = Math.max(width, ctx.measureText(lines[i]).width + doubleBorderSize)
      }
      const height = size * lines.length + doubleBorderSize
      this.label_size = { x: width / sizefactore, y: height / sizefactore }
      ctx.canvas.width = width
      ctx.canvas.height = height

      // need to set font again after resizing canvas
      ctx.font = font
      ctx.textBaseline = 'top'

      // ctx.fillStyle = 'red'
      // ctx.fillRect(0, 0, width, height)
      ctx.fillStyle = txtcolor
      for (var j = 0; j < lines.length; j++) {
        ctx.fillText(lines[j], borderSize, borderSize + j * size)
      }
      // console.log('createLabelCanvas', ctx)
      return ctx.canvas
    },
    createImgCanvas (src) {
      // let vnode = this
      return new Promise((resolve, reject) => {
        var img = new Image()
        // XSS resolution
        // https://www.html5gamedevs.com/topic/31184-solved-cors-problem-with-dynamictexture-on-some-servers-tainted-canvas/
        img.crossOrigin = 'Anonymous'
        img.src = src
        img.onload = function () {
          // console.log('img loaded', this)
          const ctx = document.createElement('canvas').getContext('2d')
          ctx.canvas.width = this.width
          ctx.canvas.height = this.height
          ctx.fillStyle = 'red'
          // ctx.fillRect(0, 0, this.width, this.height)
          ctx.drawImage(this, 0, 0, this.width, this.height)
          resolve({ img: this, canvas: ctx.canvas })
        }
        img.onerror = function () {
          reject(src)
        }
      })
    }
  }
}
