

import { 
  Vector3
} from 'three';
import { Loader3DTiles } from 'three-loader-3dtiles';
import {modelManager} from './ModelManager.js';

export default class LoaderTileFiles{
    
    constructor(scene,renderer){
        this.offset = new Vector3();    //偏移量
        this.scene = scene;
        this.tilesRuntime = null;
        this.renderer = renderer;
    }

    async loadTilesets(prefix,fileName){

        const tilesetUrl = prefix + fileName;
        const response = await fetch(tilesetUrl);
        const data = await response.json();

        if(data.root){
            if(data.root.content&&data.root.content.url.indexOf('.b3dm')>-1){
              await this.loadTileset(tilesetUrl);   //直接加载
            }
            else if(!data.root.content&&data.root.children){
                for(let i=0;i<data.root.children.length;++i){
                    const item = data.root.children[i];
                    if(item.content.uri){
                        const url = prefix + item.content.uri.replace('./','');
                        await this.loadTileset(url);   //直接加载
                    }
                    else{
                        debugger;
                    }
                }
            }
        }
    }

    async loadTileset(tilesetUrl) {
        const result = await Loader3DTiles.load(
          {
            url:tilesetUrl,
              //queryParams.get('tilesetUrl') ??
              //tilesetUrl ??
              //'https://testgis.4dage.com/LVBADUI_qp/tileset.json',  
              //'https://int.nyt.com/data/3dscenes/ONA360/TILESET/0731_FREEMAN_ALLEY_10M_A_36x8K__10K-PN_50P_DB/tileset_tileset.json',
            renderer: this.renderer,
            options: {
              dracoDecoderPath: 'https://cdn.jsdelivr.net/npm/three@0.137.0/examples/js/libs/draco',
              basisTranscoderPath: 'https://cdn.jsdelivr.net/npm/three@0.137.0/examples/js/libs/basis',
              maximumScreenSpaceError: 48, //queryParams.get('sse') ?? 48,
            }
          }
        );
    
        const {model, modelCenter, runtime} = result;
        model.rotation.set(-Math.PI / 2, 0, Math.PI / 2);
    
        // if (!queryParams.get('tilesetUrl')) {
        //   model.position.set(-1, 4, -16);
        // }
        model.position.set(modelCenter.x,modelCenter.y,modelCenter.z);
        this.tilesRuntime = runtime;
        this.scene.add(model);
        modelManager.tilesMeshesUUIDs.push(model.uuid);
    }
}