import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter'

/**
 * @class ExportGltfToLocal
 * @classdesc gltf模型导出本地文件
 */
class ExportGltfToLocal {
  constructor(_scene) {
    this.scene = _scene
    this.igltfexporter = new GLTFExporter()
  }
  exportGltf(outfilename) {
    //  导出gltf模型配置：
    const options = {
      trs: false, // true导出位置、缩放、旋转变换，false导出节点的矩阵变换
      onlyVisible: true, // 是否只导出可见的
      truncateDrawRange: true, // 是否二进制，true导出glb模型，false导出gltf模型
      binary: false, // 最大贴图尺寸
      maxTextureSize: Infinity
    }
    let that = this
    this.igltfexporter.parse(
      this.scene,
      function (result) {
        const output = JSON.stringify(result, null, 2)
        console.log(output)
        that.saveString(output, outfilename + '.gltf')
      },
      options
    )
  }
  exportGlb(outfilename) {
    // 导出glb模型配置：
    const options = {
      trs: false,
      onlyVisible: true,
      truncateDrawRange: true,
      binary: true,
      maxTextureSize: Infinity
    }
    let that = this
    this.igltfexporter.parse(
      this.scene,
      function (result) {
        that.saveArrayBuffer(result, outfilename + '.glb')
      },
      options
    )
  }
  saveArrayBuffer(buffer, filename) {
    this.save(new Blob([buffer], { type: 'application/octet-stream' }), filename)
  }
  saveString(text, filename) {
    this.save(new Blob([text], { type: 'text/plain' }), filename)
  }
  save(blob, filename) {
    const link = document.createElement('a')
    link.style.display = 'none'
    document.body.appendChild(link) // Firefox workaround, see #6594
    link.href = URL.createObjectURL(blob)
    link.download = filename
    link.click()
    // URL.revokeObjectURL( url ); breaks Firefox...
  }
}
export default ExportGltfToLocal
