export async function buttonTriggeredRequest<T>(e: MouseEvent, promise: Promise<T>) {
	(e.target as HTMLButtonElement).disabled = true;
	await promise;
	(e.target as HTMLButtonElement).disabled = false;
}

export function resizeTableColumn(event: MouseEvent, dragOffset: number) {
	const element = event.target as HTMLTableCellElement;
	const rect = element.getBoundingClientRect();

	const posX = event.clientX - rect.left;
	const offset = rect.width - event.clientX;
	if (posX <= dragOffset || posX >= rect.width - dragOffset) {
		// do not resize if resize request is on the table left or right
		if (
			(posX <= dragOffset && !element.previousElementSibling) ||
			(posX >= rect.width - dragOffset && !element.nextElementSibling)
		) {
			return;
		}

		const table = element.parentElement!.parentElement!.parentElement as HTMLTableElement;
		let resizeRow: HTMLTableRowElement;
		if (table.tBodies[0].rows[0].hasAttribute('resize-row')) {
			resizeRow = table.tBodies[0].rows[0];
		} else {
			resizeRow = table.tBodies[0].insertRow(0);
			resizeRow.setAttribute('resize-row', '');
			resizeRow.style.height = '0';
			resizeRow.style.border = '0';
			resizeRow.style.overflow = 'hidden';
			for (let i = 0; i < table.rows[0].cells.length; i++) {
				const cell = resizeRow.insertCell();
				cell.style.padding = '0';
			}

			// insert an additional to keep the zebra in place pattern which might be applied
			const zebraGhostRow = table.tBodies[0].insertRow(1);
			zebraGhostRow.hidden = true;
		}

		const resizeElement =
			resizeRow.cells[element.cellIndex - ((posX <= dragOffset) as unknown as number)];

		// eslint-disable-next-line svelte/no-inner-declarations,no-inner-declarations
		function resize(e: MouseEvent) {
			document.body.style.cursor = 'col-resize';
			resizeElement.style.width = `${offset + e.clientX}px`;
		}

		document.addEventListener('mousemove', resize);

		document.addEventListener('mouseup', () => {
			document.removeEventListener('mousemove', resize);
			document.body.style.cursor = 'initial';
		});
	}
}
