import * as THREE from "three";
import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js";
import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js";
import { LineGeometry } from "three/examples/jsm/lines/LineGeometry.js";

export default class CircleTextLabel extends THREE.Mesh {
  constructor(text, pos) {
    let res = 5;
    let point = new THREE.Vector3().copy(pos);
    const canvas = document.createElement("canvas");
    canvas.width = 128 * res;
    canvas.height = 128 * res;
    let fontSize = 68 * res;
    const ctx = canvas.getContext("2d");
    ctx.font = `800 ${fontSize}px Arial`; // 设置字体大小和类型
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillStyle = "#e44d54"; // 设置文字颜色和透明度
    ctx.fillText(text, canvas.width / 2, canvas.height / 2);

    // 步骤3: 将画布转换为纹理
    const texture = new THREE.CanvasTexture(canvas);

    // 步骤4: 创建材质并应用纹理
    const m = new THREE.MeshBasicMaterial({
      map: texture,
      transparent: true, // 允许材质透明
    });

    // const canvas_map = new THREE.Texture(canvas);
    texture.colorSpace = THREE.SRGBColorSpace;
    texture.needsUpdate = true;
    texture.anisotropy = 4;

    const g = new THREE.CircleGeometry(0.08, 128);
    g.rotateX(-Math.PI / 2);

    super(g, m);

    this.userData = text;

    const edges = new THREE.EdgesGeometry(g);

    const geometry = new LineGeometry();
    geometry.fromEdgesGeometry(edges);

    const line_m = new LineMaterial({
      color: 0xe44d54,
      linewidth: 5,
      dashed: false,
      dashScale : 0.1,
      alphaToCoverage: false,
    });

    line_m.resolution.set(window.innerWidth, window.innerHeight);

    const line_n = new LineSegments2(geometry, line_m);

    line_n.position.y += 0.5;

    this.add(line_n);
    this.userData = point.toArray();
    this.position.copy(point);
    this.name = "circle_" + text;
  }
}
