<template>
  <div>
    <mesh name="Project" :position="position">
      <geometry type="Box" :args="[size.x, size.y, size.z]" />
      <material type="MeshBasic" :color="color" :options="block_opts" />
    </mesh>
    <mesh name="Label" :position="label_position">
      <geometry type="Plane" :args="[label_size.x, label_size.y]" />
      <material type="MeshBasic" :options="label_opts">
        <texture :options="label_texture_opts" />
      </material>
    </mesh>
  </div>
</template>

<script>
import * as THREE from 'three'
// import { Object3D } from '@'

export default {
  name: 'Project',
  // mixins: [Object3D],
  // props: { size: Object, texture: String, position: Object, color: Number },
  props: { data: Object, len: Number, index: Number },
  data: () => ({
    block_opts: {
      side: THREE.DoubleSide,
      wireframe: false,
      transparent: true,
      opacity: 0.6
      // renderOrder: 0
    },
    label_opts: {
      side: THREE.DoubleSide,
      // wireframe: false,
      transparent: true
      // opacity: 0.6
      // renderOrder: 0
    },
    size: { x: 10, y: 10, z: 10 },
    position: { x: 5, y: 5, z: 0 },
    label_position: { x: 5, y: 5, z: 20 },
    color: 0xffffff,
    label_canvas: null,
    label_size: null
  }),
  computed: {
    label_texture_opts () {
      return {
        canvas: this.label_canvas,
        minFilter: THREE.LinearFilter,
        wrapS: THREE.ClampToEdgeWrapping,
        wrapT: THREE.ClampToEdgeWrapping
      }
    }
  },
  created () {
    // console.log('this.index', this.index)
    this.size.y = 20 + Math.random() * 90
    this.position.y = this.label_position.y = -10 + Math.random() * this.size.y / 2
    this.position.x = this.label_position.x = -this.len / 2 * 15 + 15 * this.index
    this.label_canvas = this.createLabelCanvas()
    console.log('this.label_canvas', this.label_canvas)
  },
  methods: {
    createLabelCanvas () {
      console.log('createLabelCanvas', this.data.Titre)
      const size = 48
      const borderSize = 2
      const ctx = document.createElement('canvas').getContext('2d')
      const font = `${size}px bold noto_sans`
      ctx.font = font
      // measure how long the name will be
      const doubleBorderSize = borderSize * 2
      const width = ctx.measureText(this.data.Titre).width + doubleBorderSize
      const height = size + doubleBorderSize
      this.label_size = { x: width / 10, y: height / 10 }
      ctx.canvas.width = width
      ctx.canvas.height = height

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

      // ctx.fillStyle = 'green'
      // ctx.fillRect(0, 0, width, height)
      ctx.fillStyle = 'white'
      ctx.fillText(this.data.Titre, borderSize, borderSize)
      // console.log('createLabelCanvas', ctx)
      return ctx.canvas
    }
  }
}
</script>
