export class Editor {
	constructor(schema) {
		this.schema = schema
		this.editor = null
	}

	render(data) {
		const options = {
			//theme: 'spectre',
			//iconlib: 'spectre',
			theme: 'barebones',
			disable_collapse: true,
			disable_properties: true,
			schema: this.schema,
		}

		// startval isn't set if this is a newly created node.
		// When setValue is called (or startval set), all widgets/fields are hidden if not defined in the JSON data. 
		// When startval isn't set, the schema properties are displayed instead.
		if (data !== undefined && data !== null)
			options.startval = data

		const div = document.createElement('div')
		this.editor = new JSONEditor(div, options);

		// this.editor.on('ready', ()=>{
		// })
		div.addEventListener('keydown', event=>this.keyHandler(event))

		return div
	}

	keyHandler(event) {
		if (!event.ctrlKey || event.key != 's')
			return
		mbus.dispatch('EDITOR_NODE_SAVE')
		event.stopPropagation()
		event.preventDefault()
	}

	data() {
		return this.editor.getValue()
	}
}
