ProfileEditor.pattern = {
	text: "^\\s*x\\s*=\\s*([-0-9.]+)\\s*,?\\s*y\\s*=\\s*([-0-9.]+).*$",
	json: "\\s*\\[\\s*([-0-9.]+)\\s*,\\s*([-0-9.]+)\\s*\\]"
}

function ProfileEditor (callback, initial_values) {
	this.parent_node = document.getElementById ("popup_screen")
	this.parent_node.style.display = "block" 
    this.node = create_node ("div", "", {class: "ProfileEditor"}, this.parent_node)
    this.callback = callback
}

ProfileEditor.prototype.start = function (initial_values) {
	this.get_dom()
	if (!initial_values)
		return
	Object.keys(initial_values).forEach( (key, i) => {
		this[key].value = initial_values[key];
	} )
	this.select_pattern.selectedIndex = 1
}

ProfileEditor.prototype.html_render = function () {
	var b, name, input_pattern, select_pattern

	create_node ("h1", "Profile Editor", {id: "profile_editor"}, this.node)
	var n = create_node ("form", "", {action: ""}, this.node)
	b = create_node("button", "Save", {style: "float:right;"}, n)
	b.addEventListener("click", () => {
		var regex = select_pattern.options[select_pattern.selectedIndex].value
		if (input_pattern.value.trim() != "")
			regex = input_pattern.value.trim()
		regex = new RegExp (regex, "igm")
		var r = []
		do {
		   var m = regex.exec(this.input.value)
		   if (m)
		   	r.push ([Number(m[1]), Number(m[2])])
	    } while (m)
		this.callback({name: name.value, data: r})
		this.parent_node.style.display = "none"
		prune_dom(this.parent_node)

	})
	b = create_node("button", "Cancel", {style: "float:right;"}, n)
	b.addEventListener("click", () => {
    	this.parent_node.style.display = "none"
		prune_dom(this.parent_node)		
	})
	create_node("label", "Profile Name:", {id: "profile_editor_name"}, n)
	name = this.name = create_node("input", "", {type: "text"}, n)
	name.focus()
	create_node("br", "", {}, n)
	create_node("label", "Other Regular Expressions:", {title: "To use as an example."}, n)
	create_node("br", "", {}, n)
	this.select_pattern = select_pattern = create_node("select", "", {}, n)
	for (var i in ProfileEditor.pattern)
			create_node("option", ProfileEditor.pattern[i], {name: i}, select_pattern)
	select_pattern.options["text"].selected = true
	create_node("br", "", {}, n)
	create_node("label", "Scan Pattern:", {title: "Regular Expression"}, n)
	create_node("br", "", {}, n)
	input_pattern = create_node("input", "", {type: "text", style: "width: 50ex"}, n)
	create_node("br", "", {}, n)
	create_node("label", "Point Coordinates:", {}, n)
	create_node("br", "", {}, n)
	this.input = create_node("textarea", "", {cols: "57", rows: "35", style: "overflow-y: auto;"}, n)
	create_node("br", "", {}, n)

	return this.node
}

ProfileEditor.prototype.get_dom = function () {
	prune_dom(this.node)
	this.html_render()
}