<template>
	<div class="wrapper" :style="wrapperStyle">
		<div ref="runtimeLayer" id="runtimeLayer" class="runtime-layer" style="line-height:0;font-size:0"></div>
	</div>
</template>

<script>
	const engine = window.engine;

	export default {
		name: "RuntimeLayer",
		props: {
			designWidth: {
				type: Number,
				default: 375,
			},
			designHeight: {
				type: Number,
				default: 667,
			},
			assetResolver: {
				type: Function,
			},
		},
		data() {
			return {}
		},
		mounted() {
			this.$nextTick(this.launch);
		},
		computed: {
			wrapperStyle() {
				return {
					width: this.designWidth + 'px',
					height: this.designHeight + 'px',
				}
			}
		},
		watch: {
			designWidth() {
				this.resize();
			},
			designHeight() {
				this.resize();
			},
		},
		methods: {
			launch() {
				engine.launchWithConfig({
					options: {
						containerId: 'runtimeLayer',
						entrySceneView: 'entry',
						editorMode: true,
						assetResolver: this.assetResolver,
						frameRate: 15,
						rendererType: 'canvas',
					},
				}, null, () => {
					this.onLaunched();
				});
			},
			onLaunched() {
				//engine.editorStage.stage.addEventListener('onMouseClick', this.onStageClick, this);
				this.$emit('launched');
			},
			onStageClick(e) {
				let node = e.currentTarget;
				let view = this.getNode('', true);
				this.$emit('select-node', node.getIndexPath(view));
			},
			resize() {
				this.$nextTick(() => {
					if(engine.editorStage){
						engine.editorStage.resizeStage();
					}
				});
			},
			showView(viewConfig) {
				if(!engine.editorStage){
					return false;
				}
				engine.editorStage.showView(viewConfig);
			},
			getNode(nodePath, origin = false) {
				return engine.editorStage.getNode(nodePath, origin);
			},
			modifyProps(nodePath, props, callback) {
				let result = engine.editorStage.modifyProps(nodePath, props);
				if (result) {
					callback()
					//setTimeout(callback, 0);
				}
				return result;
			},
			getNodePathWithPos(pos) {
				let node = engine.editorStage.getNodeWithPos(pos);

				let view = this.getNode('', true);
				return node.getIndexPath(view);
			},

		}
	}
</script>

<style scoped lang="scss">
	.runtime-layer {
		background-color: lightgray;
		//border: 1px solid lightgray;
		width: 100%;
		height: 100%;
	}
</style>
