export default Render({
  position: {
    x: 150,
    y: 150,
    vx: 2,
    vy: 2,
  },
  x: -100,

  async renderCar() {
    let canvasCar = await getCanvasById('canvas')
    let width = canvasCar.width
    let height = canvasCar.height

    let ctx = canvasCar.getContext('2d')

    let dpr = 1
    canvasCar.width = width * dpr
    canvasCar.height = height * dpr
    ctx.scale(dpr, dpr)

    let renderLoop = () => {
      this.render(canvasCar, ctx)
      canvasCar.requestAnimationFrame(renderLoop)
    }
    canvasCar.requestAnimationFrame(renderLoop)

    let img = canvas.createImage()
    img.onload = () => {
      this._img = img
    }
    img.src = './car.png'
  },

  render(canvas = null, ctx) {
    ctx.clearRect(0, 0, 300, 300)
    this.drawBall(ctx)
    this.drawCar(ctx)
  },

  drawBall(ctx) {
    let p = this.position
    p.x += p.vx
    p.y += p.vy
    if (p.x >= 300) {
      p.vx = -2
    }
    if (p.x <= 7) {
      p.vx = 2
    }
    if (p.y >= 300) {
      p.vy = -2
    }
    if (p.y <= 7) {
      p.vy = 2
    }

    function ball(x, y) {
      ctx.beginPath()
      ctx.arc(x, y, 5, 0, Math.PI * 2)
      ctx.fillStyle = '#1aad19'
      ctx.strokeStyle = 'rgba(1,1,1,0)'
      ctx.fill()
      ctx.stroke()
    }

    ball(p.x, 150)
    ball(150, p.y)
    ball(300 - p.x, 150)
    ball(150, 300 - p.y)
    ball(p.x, p.y)
    ball(300 - p.x, 300 - p.y)
    ball(p.x, 300 - p.y)
    ball(300 - p.x, p.y)
  },

  drawCar(ctx) {
    if (!this._img) return
    if (this.x > 350) {
      this.x = -100
    }
    ctx.drawImage(this._img, this.x++, 150 - 25, 100, 50)
    ctx.restore()
  },

  async renderImageData() {
    let canvas3 = await getCanvasById('canvas3')
    let ctx = canvas3.getContext('2d')
    let imgData = ctx.createImageData(100, 100)
    for (i = 0; i < imgData.width * imgData.height * 4; i += 4) {
      imgData.data[i + 0] = 255
      imgData.data[i + 1] = 0
      imgData.data[i + 2] = 0
      imgData.data[i + 3] = 155
    }
    ctx.putImageData(imgData, 50, 50)
  },
})
