const { ipcRenderer } = require('electron');
let json_data;
let tables_data;
let current_table;
let selected_cells = [];
let selected_cell_data;
let is_positioning = false;
let nav = $("nav");
let nav_scroll = nav.scrollLeft();
let detail_tab_name = $("#detail-tab-name");
let detail_table_name = $("#detail-table-name");
let detail_table_hidden = $("#detail-table-hidden");
let detail_column_name = $("#detail-column-name");
let detail_column_selectable = $("#detail-column-selectable");
let detail_column_sortable = $("#detail-column-sortable");
let detail_cell_text = $("#detail-cell-text");
let position_edit_btn = $("#position-edit");

function openFile(file) {
	if (typeof file == "object") {
		json_data = file;
		tables_data = file["tables"];
		current_table = null;
		refreshPage();
	} else {
		$.ajax({
			dataType: "json",
			url: file,
			cache: false,
			success: (json, textStatus, jqXHR) => {
				json_data = json;
				tables_data = json["tables"];
				current_table = null;
				refreshPage();
			}
		});
	}
}

function saveFile(create_new_file) {
	ipcRenderer.send("save", json_data, create_new_file);
}

function clearPage() {
	$("#tables").empty();
	nav.empty();
	$("#details input, #details textarea").val("");
	selected_cells = [];
	selected_cell_data = null;
}

function refreshPage() {
	toggleMovement();
	clearPage();
	generateTables();
	showTab(current_table ? current_table: tables_data[0]["id"]);
	toggleMovement()
}

function generateTable(table_data, table_index) {
	const table_id = table_data["id"];
	let a = $("<a></a>")
		.attr("id", table_id + "-nav")
		.addClass("nav-link table-nav")
		.attr("href", "#" + table_id)
		.text(table_data["name"])
		.on("click", () => {
			showTab(table_id);
		})
		.on("contextmenu", (event) => {
			navContextMenu(event, table_id);
		});
	let add_table_btn = nav.find("a[id='add-table']");
	if (add_table_btn.length !== 0) {
		add_table_btn.before(a);
	} else {
		nav.append(a);
	}

	let table_div = $("<div></div>")
		.attr("id", table_id + "-tab")
		.addClass("tab-pane table-responsive text-nowrap")
		.css({"margin-right": "100px"});

	let table = $("<table></table>")
		.attr("id", table_id)
		.addClass("table table-bordered")
		.append($("<thead></thead>")
			.append($("<tr></tr>")
				.addClass("text-nowrap")))
		.append("<tbody>");

	$.each(table_data["columns"], (i, col) => {
		const col_id = col["field"];
		let header_id = table_id + "-" + col_id;
		table.find("thead > tr")
			.append(makeHeader(header_id, i, col["title"]));
	})

	$.each(table_data["rows"], (i, row) => {
		const row_id = row["uid"];
		let tr = $("<tr></tr>")
			.attr("id", table_id + "-" + row_id);
		$.each(table_data["columns"], (j, col) => {
			const col_id = col["field"];
			let cell_id = table_id + "-" + col_id + "-" + row_id;
			let td = makeCell(cell_id, row[col_id]);
			tr.append(td);
		})
		table.find("tbody").append(tr);
	})

	table_div.append(table);
	let table_container = $("#tables");
	let add_row_div = table_container.find("div[id='add-row-div']");
	if (add_row_div.length !== 0) {
		add_row_div.before(table_div);
	} else {
		table_container.append(table_div);
	}
}

function makeCell(cell_id, cell_text) {
	return $("<td></td>")
		.attr("id", cell_id)
		.text(cell_text)
		.on("click", () => {
			selectCell(cell_id);
		})
		.on("contextmenu" , (event) => {
			cellContextMenu(event, cell_id);
		})
		.on("dblclick", (event) => {
			cellInlineEdit(event);
		});
}

function makeHeader(header_id, header_index, col_title) {
	return $("<th>")
		.attr("id", header_id)
		.css("user-select", "none")
		.text(col_title)
		.on("click", () => {
			selectCell(header_id);
		})
		.on("contextmenu", (event) => {
			headerContextMenu(event, header_id);
		})
		.on("dblclick", (event) => {
			headerInlineEdit(event);
		});
}

function generateTables() {
	$("#tables").append($("<div>")
		.attr("id", "add-col-div")
		.css({"position": "absolute", "top": "46px", "right": "0"})
		.append($("<button>")
			.attr("id", "btn-add-column")
			.addClass("btn btn-primary")
			.text("add column")
			.on("click", () => {
				insertColumn(current_table, -1)
			})))
	$.each(tables_data, (i, table_data) => {
		generateTable(table_data, i);
	})
	$("#tables").append($("<div>")
		.attr("id", "add-row-div")
		.append($("<button>")
			.attr("id", "btn-add-row")
			.addClass("btn btn-primary")
			.text("add row")
			.on("click", () => {
				insertRow(current_table, -1)
			})))
	nav.append($("<a></a>")
		.attr("id", "add-table")
		.addClass("nav-link btn btn-success")
		.html("<i class='fa fa-plus'></i>")
		.attr({"data-bs-toggle": "tooltip", "data-bs-placement": "bottom", "title": "add table"})
		.on("click", () => {
			addTable();
		}))
}

function updateDetailsPanel() {
	let data = getSelectedCellData();
	detail_tab_name.val(data["tab_name"]);
	detail_table_name.val(data["table_name"]);
	detail_column_name.val(data["col_name"]);
	detail_table_hidden.prop("checked", data["table_hidden"]);
	detail_column_selectable.prop("checked", data["col_selectable"]);
	detail_column_sortable.prop("checked", data["col_sortable"]);
	if (data["row_id"]) {
		detail_cell_text.attr("disabled", false);
		detail_cell_text.val(data["cell_text"]);
	} else {
		detail_cell_text.attr("disabled", true);
		detail_cell_text.val("");
	}
}

function showTab(table_name) {
	current_table = table_name;
	let tab_name = table_name+"-tab";
	$("#tables").children().removeClass("show active");
	nav.children().removeClass("active");
	$("#"+tab_name).addClass("show active");
	$("#"+tab_name.replace("-tab", "-nav")).addClass("active");
	selectCell($("table:visible > tbody > tr:first > td:first").attr("id"));
}

function selectCell(cell_id) {
	$("td, th").removeClass("selected");
	$("#"+cell_id).addClass("selected");
	selected_cells = [cell_id];
	updateDetailsPanel();
}

function getSelectedCellData(force_update=false) {
	if (!force_update && selected_cell_data && selected_cells[0] === selected_cell_data["selected_id"]) {
		return selected_cell_data;
	}
	let table_pattern = /(table\d+)/;
	let column_pattern = /(column\d+)/;
	let row_pattern = /(row\d+)/;
	let table_match = table_pattern.exec(selected_cells[0]);
	let column_match = column_pattern.exec(selected_cells[0]);
	let row_match = row_pattern.exec(selected_cells[0]);
	let cell_data = {
		"selected_id": selected_cells[0],
		"table_id": table_match[0],
		"table_nav_id": table_match[0]+"-nav",
		"col_id": table_match[0]+"-"+column_match[0],
		"num_tables": tables_data.length,
	}
	$.each(tables_data, (i, table_data) => {
		if (table_data["id"] === table_match[0]) {
			cell_data["table_index"] = i;
			cell_data["table_name"] = table_data["name"];
			cell_data["tab_name"] = table_data["tab_name"];
			cell_data["table_hidden"] = table_data["hidden"];
			cell_data["num_rows"] = table_data["rows"].length;
			cell_data["num_cols"] = table_data["columns"].length;
			$.each(table_data["columns"], (j, col) => {
				if (col["field"] === column_match[0]) {
					cell_data["col_index"] = j;
					cell_data["col_name"] = col["title"];
					cell_data["col_selectable"] = col["selectable"];
					cell_data["col_sortable"] = col["sortable"];
					return false;
				}
			})
			if (row_match !== null) {
				cell_data["row_id"] = table_match[0]+"-"+row_match[0];
				cell_data["cell_id"] = table_match[0]+"-"+column_match[0]+"-"+row_match[0];
				$.each(table_data["rows"], (j, row) => {
					if (row["uid"] === row_match[0]) {
						cell_data["row_index"] = j;
						cell_data["cell_text"] = row[column_match[0]];
						cell_data["row_key"] = column_match[0];
						return false;
					}
				})
			}
			return false;
		}
	})
	selected_cell_data = cell_data;
	return selected_cell_data;
}

function addTable() {
	let table_ids = getTableIDs();
	let table_num = 0;
	for (let id of table_ids) {
		if (table_ids.includes(`table${table_num}`)) {
			table_num++;
		} else {break;}
	}
	let table_id = `table${table_num}`;
	let table_data = {
		"id": table_id,
		"name": "New Table",
		"filter": false,
		"hidden": false,
		"tab_name": "",
		"description": "",
		"columns": [
			{
				"field": "column0",
				"title": "Column 1",
				"sortable": true,
				"selectable": false
			}
		],
		"rows": [
			{
				"uid": "row0",
				"column0": "",
			}
		]
	}
	tables_data.push(table_data);
	getSelectedCellData(true);
	generateTable(table_data);
}

function duplicateTable(table_id) {
	for (let i=0; i < tables_data.length; i++) {
		if (tables_data[i]["id"] === table_id) {
			let new_table = JSON.parse(JSON.stringify(tables_data[i]));
			let table_ids = getTableIDs();
			let table_num = 0;
			for (let id of table_ids) {
				if (table_ids.includes(`table${table_num}`)) {
					table_num++;
				} else {break;}
			}
			new_table["id"] = `table${table_num}`;
			new_table["name"] = "copy of "+new_table["name"];
			tables_data.splice(i+1, 0, new_table);
			break;
		}
	}
	refreshPage();
}

function insertColumn(table_id, index=-1) {
	$.each(tables_data, (i, table_data) => {
		if (table_data["id"] === table_id) {
			if (index === -1) {index = table_data["columns"].length}
			let col_ids = getColumnIDs(table_data["columns"]);
			let col_num = 0;
			for (let id of col_ids) {
				if (col_ids.includes(`column${col_num}`)) {
					col_num++;
				} else {break;}
			}
			let col_id = `column${col_num}`
			table_data["columns"].splice(index, 0,{
				"field": col_id,
				"title": "New Column",
				"sortable": false,
				"selectable": false,
			})

			let num_cols = $(`#${table_id} > thead > tr`).children().length;
			if (index >= num_cols) {
				index = num_cols-1;
				$.fn.insert = function (data) {
					this.after(data);
				};
			} else {
				$.fn.insert = function (data) {
					this.before(data);
				};
			}
			let header_id = table_id + "-" + col_id;
			$(`#${table_id} > thead > tr > th:nth-child(${index + 1})`)
				.insert(makeHeader(header_id, index, "New Column"));

			$(`#${table_id} > tbody > tr`).each((j, tr) => {
				tr = $(tr);
				let cell_id = table_id+"-"+col_id+"-"+table_data["rows"][j]["uid"];
				tr.children(`td:nth-child(${index + 1})`)
					.insert(makeCell(cell_id, ""))
			});
			getSelectedCellData(true);
			return false;
		}
	})
}

function insertRow(table_id, index) {
	$.each(tables_data, (i, table_data) => {
		if (table_data["id"] === table_id) {
			if (index === -1) {index = table_data["rows"].length}
			let row_ids = getRowIDs(table_data["rows"]);
			let row_num = 0;
			for (let id of row_ids) {
				if (row_ids.includes(`row${row_num}`)) {
					row_num++;
				} else {break;}
			}
			let row_id = `row${row_num}`
			let col_ids = getColumnIDs(table_data["columns"]);
			let row_data = {"uid": row_id};
			for (let id of col_ids) {
				row_data[id] = "";
			}
			table_data["rows"].splice(index, 0, row_data);

			let num_rows = $(`#${table_id} > tbody > tr`).length;
			if (index >= num_rows) {
				index = num_rows-1;
				$.fn.insert = function (data) {
					this.after(data);
				};
			} else {
				$.fn.insert = function (data) {
					this.before(data);
				};
			}
			let tr = $("<tr></tr>")
				.attr("id", table_id+"-"+row_id);
			for (let col_id of col_ids) {
				let cell_id = table_id+"-"+col_id+"-"+row_id;
				tr.append(makeCell(cell_id, ""))
			}
			$(`#${table_id} > tbody > tr:nth-child(${index+1})`)
				.insert(tr);
			getSelectedCellData(true);
			return false;
		}
	})
}

function deleteTable(table_id) {
	for (let i=0; i<tables_data.length; i++) {
		if (tables_data[i]["id"] === table_id) {
			tables_data.splice(i, 1);
			if (table_id === current_table) {
				current_table = null;
			}
		}
	}
	refreshPage();
}

function deleteColumn(table_id, col_index) {
	for (let table_data of tables_data) {
		if (table_data["id"] === table_id) {
			let field = table_data["columns"][col_index]["field"];
			table_data["columns"].splice(col_index, 1);

			for (let row of table_data["rows"]) {
				delete row[field];
			}
			break;
		}
	}
	refreshPage();
}

function deleteRow(table_id, row_index) {
	for (let table_data of tables_data) {
		if (table_data["id"] === table_id) {
			table_data["rows"].splice(row_index, 1);
			break;
		}
	}
	refreshPage();
}

function cellContextMenu(event, cell_id) {
	if (is_positioning) {return;}
	if (!selected_cells.includes(cell_id)) {
		selectCell(cell_id);
	}
	let menu = $("<div>")
		.attr("id", "context-menu-"+cell_id)
		.addClass("border context-menu text-nowrap list-group")
		.on("mouseleave", () => {
			menu.remove();
		})
		.append($("<button>")
			.addClass("list-group-item list-group-item-action")
			.on("click", () => {
				let data = getSelectedCellData();
				insertRow(data["table_id"], data["row_index"]);
			})
			.text("Insert row above"))
		.append($("<button>")
			.addClass("list-group-item list-group-item-action")
			.on("click", () => {
				let data = getSelectedCellData();
				insertRow(data["table_id"], data["row_index"]+1);
			})
			.text("Insert row below"))
		.append($("<button>")
			.addClass("list-group-item list-group-item-action")
			.on("click", () => {
				let data = getSelectedCellData();
				insertColumn(data["table_id"], data["col_index"]);
			})
			.text("Insert column left"))
		.append($("<button>")
			.addClass("list-group-item list-group-item-action")
			.on("click", () => {
				let data = getSelectedCellData();
				insertColumn(data["table_id"], data["col_index"]+1);
			})
			.text("Insert column right"))
	let data = getSelectedCellData();
	if (data["num_cols"] > 1) {
		menu.append($("<button>")
			.addClass("list-group-item list-group-item-action list-group-item-danger")
			.on("click", () => {
				let data = getSelectedCellData();
				deleteColumn(data["table_id"], data["col_index"]);
				menu.remove();
			})
			.text("Delete column"))
	}
	if (data["num_rows"] > 1) {
		menu.append($("<button>")
			.addClass("list-group-item list-group-item-action list-group-item-danger")
			.on("click", () => {
				let data = getSelectedCellData();
				deleteRow(data["table_id"], data["row_index"]);
				menu.remove();
			})
			.text("Delete row"));
	}

	let max_height = $(document).height();
	let max_width = $(document).width();
	let x_pos = event.pageX-5;
	let y_pos = event.pageY-5;
	$("body").append(menu);
	y_pos = Math.min(y_pos, max_height-menu.height());
	x_pos = Math.min(x_pos, max_width-menu.width());
	menu.css({"top": y_pos, "left": x_pos});
}

function headerContextMenu(event, header_id) {
	if (is_positioning) {return;}
	if (!selected_cells.includes(header_id)) {
		selectCell(header_id);
	}
	let menu = $("<div>")
		.attr("id", "context-menu-"+header_id)
		.addClass("border context-menu text-nowrap list-group")
		.on("mouseleave", () => {
			menu.remove();
		})
		.append($("<button>")
			.addClass("list-group-item list-group-item-action")
			.on("click", () => {
				let data = getSelectedCellData();
				insertColumn(data["table_id"], data["col_index"]);
			})
			.text("Insert column left"))
		.append($("<button>")
			.addClass("list-group-item list-group-item-action")
			.on("click", () => {
				let data = getSelectedCellData();
				insertColumn(data["table_id"], data["col_index"]+1);
			})
			.text("Insert column right"));

	let data = getSelectedCellData();
	if (data["num_cols"] > 1) {
		menu.append($("<button>")
			.addClass("list-group-item list-group-item-action list-group-item-danger")
			.on("click", () => {
				let data = getSelectedCellData();
				deleteColumn(data["table_id"], data["col_index"]);
				menu.remove();
			})
			.text("Delete column"))
	}

	let max_height = $(document).height();
	let max_width = $(document).width();
	let x_pos = event.pageX-5;
	let y_pos = event.pageY-5;
	$("body").append(menu);
	y_pos = Math.min(y_pos, max_height-menu.height());
	x_pos = Math.min(x_pos, max_width-menu.width());
	menu.css({"top": y_pos, "left": x_pos});
}

function navContextMenu(event, table_id) {
	if (is_positioning) {return;}
	let data = getSelectedCellData();
	let menu = $("<div>")
		.attr("id", "context-menu-"+table_id)
		.addClass("border context-menu text-nowrap list-group")
		.on("mouseleave", () => {
			menu.remove();
		})
		.append($("<button>")
			.addClass("list-group-item list-group-item-action")
			.text("duplicate table")
			.on("click", () => {
				duplicateTable(table_id);
			}));
	if (data["num_tables"] > 1) {
		menu.append($("<button>")
			.addClass("list-group-item list-group-item-action list-group-item-danger")
			.text("Delete Table")
			.attr({"data-bs-toggle": "modal", "data-bs-target": "#delete-table"})
			.on("click", () => {
				$("#confirm-delete-table").one("click", (event) => {
					deleteTable(table_id);
				})
				menu.remove();
			}));
	}
	let max_height = $(document).height();
	let max_width = $(document).width();
	let x_pos = event.pageX-5;
	let y_pos = event.pageY-5;
	$("body").append(menu);
	y_pos = Math.min(y_pos, max_height-menu.height());
	x_pos = Math.min(x_pos, max_width-menu.width());
	menu.css({"top": y_pos, "left": x_pos});
}

function cellInlineEdit(event) {
	if (is_positioning) {return;}
	let data = getSelectedCellData()
	let target = $(event.target);
	let text_area = $("<textarea>")
		.on("focusout", () => {
			closeCellInlineEdit(true);
		})
		.on("keydown", (event) => {
			if (event.key === "Escape") {
				closeCellInlineEdit(false);
			} else if (event.key === "Enter" && !event.shiftKey) {
				closeCellInlineEdit(true);
			}
		})
		.val(data["cell_text"]);
	target.html(text_area)
		.addClass("inline-edit");
	text_area.focus();
}

function closeCellInlineEdit(save=false) {
	if (save) {
		let val = $("td.inline-edit > textarea").val()
		$("td.inline-edit").html(val)
			.removeClass("inline-edit");
		let data = getSelectedCellData();
		tables_data[data["table_index"]]["rows"][data["row_index"]][data["row_key"]] = val;
		selected_cell_data["cell_text"] = val;
		detail_cell_text.val(val);
	} else {
		let data = getSelectedCellData();
		$("td.inline-edit").removeClass("inline-edit")
			.html(data["cell_text"]);
	}
}

function headerInlineEdit(event) {
	if (is_positioning) {return;}
	let data = getSelectedCellData()
	let target = $(event.target);
	let text_area = $("<textarea>")
		.on("focusout", () => {
			closeHeaderInlineEdit(true);
		})
		.on("keydown", (event) => {
			if (event.key === "Escape") {
				closeHeaderInlineEdit(false);
			} else if (event.key === "Enter" && !event.shiftKey) {
				closeHeaderInlineEdit(true);
			}
		})
		.val(data["col_name"]);
	target.html(text_area)
		.addClass("inline-edit");
	text_area.focus();
}

function closeHeaderInlineEdit(save=false) {
	if (save) {
		let val = $("th.inline-edit > textarea").val()
		$("th.inline-edit").html(val)
			.removeClass("inline-edit");
		let data = getSelectedCellData();
		tables_data[data["table_index"]]["columns"][data["col_index"]]["title"] = val;
		selected_cell_data["col_name"] = val;
		detail_column_name.val(val);
	} else {
		let data = getSelectedCellData();
		$("th.inline-edit").removeClass("inline-edit")
			.html(data["col_name"]);
	}
}

function moveTable(old_index, new_index) {
	let table_data = tables_data[old_index];
	tables_data.splice(old_index, 1);
	tables_data.splice(new_index, 0, table_data);
	getSelectedCellData(true);
}

function moveRow(table_id, old_index, new_index) {
	for (let table_data of tables_data) {
		if (table_data["id"] === table_id) {
			let row = table_data["rows"][old_index];

			table_data["rows"].splice(old_index, 1);
			table_data["rows"].splice(new_index, 0, row);
		}
	}
	getSelectedCellData(true);
}

function moveCol(table_id, old_index, new_index) {
	for (let table_data of tables_data) {
		if (table_data["id"] === table_id) {
			let col = table_data["columns"][old_index];
			table_data["columns"].splice(old_index, 1);
			table_data["columns"].splice(new_index, 0, col);
		}
	}
	refreshPage();
}

function enableMovement() {
	is_positioning = true;
	$("table > tbody").each((i, elm) => {
		Sortable.create(elm, {
			animation: 50,
			easing: "cubic-bezier(1, 0, 0, 1)",
			onEnd: function (event) {
				moveRow(current_table, event.oldIndex, event.newIndex);
			}
		});
	})
	$("table > thead > tr").each((i, elm) => {
		Sortable.create(elm, {
			animation: 50,
			easing: "cubic-bezier(1, 0, 0, 1)",
			onEnd: function (event) {
				moveCol(current_table, event.oldIndex, event.newIndex);
			}
		});
	})
	Sortable.create($("nav")[0], {
		animation: 50,
		easing: "cubic-bezier(1, 0, 0, 1)",
		draggable: ".table-nav",
		onend: function (event) {
			moveTable(event.oldIndex, event.newIndex);
		}
	})
	position_edit_btn.text("Stop Edit Position");
}

function disableMovement() {
	is_positioning = false;
	$("table > tbody").each((i, elm) => {
		let sortable_tbody = Sortable.get(elm);
		if (sortable_tbody) {
			sortable_tbody.destroy();
		}
	})
	$("table > thead > tr").each((i, elm) => {
		let sortable_thead = Sortable.get(elm);
		if (sortable_thead) {
			sortable_thead.destroy();
		}
	})
	let sortable_nav = Sortable.get($("nav")[0]);
	if (sortable_nav) {
		sortable_nav.destroy();
	}
	position_edit_btn.text("Start Edit Position");
}

function toggleMovement() {
	if (is_positioning) {
		disableMovement();
	} else {
		enableMovement();
	}
}

function getColumnIDs(columns) {
	let ids = [];
	for (let col of columns) {
		ids.push(col["field"]);
	}
	return ids;
}

function getRowIDs(rows) {
	let ids = [];
	for (let row of rows) {
		ids.push(row["uid"]);
	}
	return ids;
}

function getTableIDs() {
	let ids = [];
	for (let table of tables_data) {
		ids.push(table["id"]);
	}
	return ids;
}

nav.on("wheel", (event) => {
	event.preventDefault();
	if (event.originalEvent.deltaY > 0) {
		nav_scroll += 100;
		nav_scroll = Math.min(nav_scroll, nav.prop("scrollWidth") - nav.width());
		let speed = nav_scroll - nav.scrollLeft();
		nav.stop();
		nav.animate({scrollLeft: nav_scroll}, {speed: speed, easing: "linear"});
	} else {
		nav_scroll -= 100;
		nav_scroll = Math.max(nav_scroll, 0);
		let speed = nav.scrollLeft() - nav_scroll;
		nav.stop();
		nav.animate({scrollLeft: nav_scroll}, {speed: speed, easing: "linear"});
	}
});

detail_tab_name.on("input", (event) => {
	let input = $(event.target);
	let new_tab_name = input.val();
	let data = getSelectedCellData();
	tables_data[data["table_index"]]["tab_name"] = new_tab_name;
	selected_cell_data["tab_name"] = new_tab_name;
});

detail_table_name.on("input", (event) => {
	let input = $(event.target);
	let new_table_name = input.val();
	let data = getSelectedCellData();
	$(`#${data["table_nav_id"]}`).text(new_table_name);
	tables_data[data["table_index"]]["name"] = new_table_name;
	selected_cell_data["table_name"] = new_table_name;
});

detail_table_hidden.on("input", (event) => {
	let input = $(event.target);
	let table_hidden = input.prop("checked");
	let data = getSelectedCellData();
	tables_data[data["table_index"]]["hidden"] = table_hidden;
	selected_cell_data["table_hidden"] = table_hidden;
});

detail_column_name.on("input", (event) => {
	let input = $(event.target);
	let new_col_name = input.val();
	let data = getSelectedCellData();
	$(`#${data["col_id"]}`).text(new_col_name);
	tables_data[data["table_index"]]["columns"][data["col_index"]]["title"] = new_col_name;
	selected_cell_data["col_name"] = new_col_name;
});

detail_column_selectable.on("input", (event) => {
	let input = $(event.target);
	let column_selectable = input.prop("checked");
	let data = getSelectedCellData();
	tables_data[data["table_index"]]["columns"][data["col_index"]]["selectable"] = column_selectable;
	selected_cell_data["col_selectable"] = column_selectable;
});

detail_column_sortable.on("input", (event) => {
	let input = $(event.target);
	let column_sortable = input.prop("checked");
	let data = getSelectedCellData();
	tables_data[data["table_index"]]["columns"][data["col_index"]]["sortable"] = column_sortable;
	selected_cell_data["col_sortable"] = column_sortable;
});

detail_cell_text.on("input", (event) => {
	let input = $(event.target);
	let new_cell_text = input.val();
	let data = getSelectedCellData();
	$(`#${data["cell_id"]}`).text(new_cell_text);
	tables_data[data["table_index"]]["rows"][data["row_index"]][data["row_key"]] = new_cell_text;
	selected_cell_data["cell_text"] = new_cell_text;
});

position_edit_btn.on("click", () => {
	toggleMovement();
})

ipcRenderer.on("open-default", (event) => {
	openFile("default.json");
});

ipcRenderer.on("open", (event, json) => {
	openFile(json);
})

ipcRenderer.on("save", (event, create_new_file) => {
	saveFile(create_new_file);
});
