import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

// 设置轨道控制器
export function setControls (
  type: 'add' | 'delete',
  env: any,
  target?: any
) {
  const context = env.getContext()
  
  if (type === 'add') {
    const controls = new OrbitControls(context.camera, context.renderer2d.domElement)
    controls.target = target
    context.controls = controls
    return
  }

  if (type === 'delete') {

    if(context.controls){
      context.controls.dispose();
      context.controls = null;
    }
  }

}

// 获取摄像机的视觉距离
export function getDistance (env) {

  const context = env.getContext()

  const pt1 = context.camera.position
  const pt2 = context.controls.target

  return pt1.distanceTo(pt2)

}

// 判断点是否在曲线上
export const getClosetPoint = (line, dline, point) => {

  let min = null
  let closest = null
  let direct = null
  let progress = null
  const maxPec = 1000

  for (let i = 0; i < maxPec; i++) {

    const xpt = line.getPointAt(i / maxPec)

    const vpt = (new THREE.Vector3()).copy(xpt)
    vpt.y += 60

    const distance = vpt.distanceTo(point)

    if (min === null || distance < min) {
      min = distance
      closest = xpt
      direct = dline.getPointAt(i / maxPec)
      progress = i / maxPec
    }

  }

  return { min, point: closest, direct, progress }
 
}
