import * as THREE from "three";
import { getWrapText } from "../../utils/text";

export default class PureTextLabel extends THREE.Mesh {
  constructor(text, point, fontsize = 12, color = "#000000", id) {
    const radio = fontsize / 12;

    let containerWidth = 1.5 * radio;
    let containerHeight = 0.12 * radio;
    const containerRadio = containerWidth / containerHeight;
    let res = 2;
    const width = 168 * res * radio;
    const height = width / containerRadio;
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;

    let fontFamily = "Arial";
    let fs = 12 * res * radio;
    var context = canvas.getContext("2d");

    const lines = getWrapText(context, text, 140);
    console.log("lines", lines);
    containerHeight = containerHeight * lines.length;
    canvas.height = height * lines.length;
    context.fillStyle = "transparent";
    // context.fillStyle = "rgba(255,255,255,0.5)";
    context.rect(0, 0, width, height * lines.length);
    context.fill();
    let fontStyle = "normal " + fs + "px " + fontFamily;
    // console.log("fontStyle", fontStyle);
    context.font = fontStyle;
    context.fillStyle = color;
    context.textAlign = "center";
    context.textBaseline = "middle";
    // context.fillText(text, width / 2, height / 2);
    lines.forEach((txt, index) => {
      context.fillText(txt, width / 2, height / 2 + height * index);
    });
    const canvas_map = new THREE.Texture(canvas);
    canvas_map.colorSpace = THREE.SRGBColorSpace;
    canvas_map.needsUpdate = true;
    canvas_map.anisotropy = 4;

    const g = new THREE.PlaneGeometry(containerWidth, containerHeight);

    g.rotateX(-Math.PI / 2);

    // const texture = new THREE.CanvasTexture(canvas_map);

    const m = new THREE.MeshBasicMaterial({
      map: canvas_map,
      transparent: true, // 允许材质透明
    });

    super(g, m);

    if (id) {
      this.uuid = id;
    }
    const p = new THREE.Vector3().copy(point);
    this.userData = {
      id: this.uuid,
      text: text,
      color: color,
      pos: p.toArray(),
      fontsize: fontsize,
    };
    this.position.copy(p);

    this.name = "pureText_" + text;
  }
}
