/**
 * Created by rockyl on 2018-12-04.
 */

import {destroyScene, setupScene, } from "./interpreter";
import {addLoader, cacheRes, destroyRes, getAllResUuids, loadJson5} from "../assets-manager";
import {getRoot, pause, Scene, start} from "../core";

export * from './interpreter'

let currentScene: Scene;
let resUUIDs;

/**
 * 启动场景
 * @param name
 * @param progress
 */
export async function launchScene(name, progress?) {
	const scene = await loadScene(`scenes/${name}.scene`, 'scene_' + name);

	resUUIDs = getAllResUuids();

	await scene.loadResGroup('preload', progress);

	if(currentScene){
		unmountScene(currentScene);
	}

	currentScene = scene;
	mountScene(scene);

	scene.loadResGroup('delay', progress);
}

/**
 * 装载场景
 * @param scene
 */
export function mountScene(scene){
	pause();
	setupScene(scene, getRoot());
	start();
}

/**
 * 卸载场景
 * @param scene
 */
export function unmountScene(scene){
	pause();
	destroyScene(scene);
	destroyRes(resUUIDs);
}

/**
 * 加载场景资源
 * @param url url
 * @param uuid 唯一名
 * @param cache 是否缓存
 * @param config
 * @return Promise<any> 资源
 */
async function loadScene(url, uuid?, cache = false, config?) {
	const sceneConfig = await loadJson5(url);

	const scene = new Scene();
	scene.initByConfig(sceneConfig);
	return scene;
}

/**
 * 加载预制资源
 * @param url url
 * @param uuid 唯一名
 * @param cache 是否缓存
 * @param config
 * @return Promise<any> 资源
 */
export async function loadPrefab(url, uuid?, cache = true, config?) {
	let data = await loadJson5(url, uuid, false);
	cacheRes(data, url, uuid);
	return data;
}

addLoader('.pfb', loadPrefab);
