<%#
 Copyright 2018-2019 Lienol <lawlienol@gmail.com>
 Licensed to the public under the Apache License 2.0.
-%>
<script type="text/javascript">
	//<![CDATA[
	window.addEventListener('load', function () {
		const doms = document.getElementsByClassName('pingtime');
		const ports = document.getElementsByClassName("socket-connected");
		const transports = document.getElementsByClassName("transport");
		const wsPaths = document.getElementsByClassName("wsPath");
		const tlss = document.getElementsByClassName("tls");
		const xhr = (index) => {
			return new Promise((res) => {
				const dom = doms[index];
				const port = ports[index];
				const transport = transports[index];
				const wsPath = wsPaths[index];
				const tls = tlss[index];
				if (!dom) res();
				port.innerHTML = '<font style=\"color:#0072c3\">connect</font>';
				XHR.get('<%=luci.dispatcher.build_url("admin/services/shadowsocksr/ping")%>', {
					index,
					domain: dom.getAttribute("hint"),
					port: port.getAttribute("hint"),
					transport: transport.getAttribute("hint"),
					wsPath: wsPath.getAttribute("hint"),
					tls: tls.getAttribute("hint")
				},
				(x, result) => {
					let col = '#ff0000';
					if (result.ping) {
						if (result.ping < 300) col = '#ff3300';
						if (result.ping < 200) col = '#ff7700';
						if (result.ping < 100) col = '#249400';
					}
					dom.innerHTML = `<font style=\"color:${col}\">${(result.ping ? result.ping : "--") + " ms"}</font>`;
					if (result.socket) {
						port.innerHTML = '<font style=\"color:#249400\">ok</font>';
					} else {
						port.innerHTML = '<font style=\"color:#ff0000\">fail</font>';
					}
					res();
				});
			});
		};
		let task = -1;
		const thread = () => {
			task = task + 1;
			if (doms[task]) {
				xhr(task).then(thread);
			}
		};
		for (let i = 0; i < 20; i++) {
			thread();
		}
	});

	function cbi_row_drop(fromId, toId, store, isToBottom) {
		var fromNode = document.getElementById(fromId);
		var toNode = document.getElementById(toId);
		if (!fromNode || !toNode) return false;

		var table = fromNode.parentNode;
		while (table && table.nodeName.toLowerCase() != "table")
			table = table.parentNode;
		if (!table) return false;

		var ids = [];
		if (isToBottom) {
			toNode.parentNode.appendChild(fromNode);
		} else {
			fromNode.parentNode.insertBefore(fromNode, toNode);
		}
		for (var idx = 1; idx < table.rows.length; idx++) {
			table.rows[idx].className = table.rows[idx].className.replace(
				/cbi-rowstyle-[12]/,
				"cbi-rowstyle-" + (1 + (idx % 2))
			);

			if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/))
				ids.push(RegExp.$1);
		}
		var input = document.getElementById(store);
		if (input) input.value = ids.join(" ");
		return false;
	}

	// set tr draggable
	function enableDragForTable(table_selector, store) {
		// 添加 CSS 样式
		const style = document.createElement("style");
		style.textContent = `
			tr[draggable="true"] {
				cursor: move;
				user-select: none;
			}
			/* 添加置顶和置底按钮的间距 */
			.cbi-button-top, 
			.cbi-button-bottom {
				margin-right: 4px;
				display: inline-block;
			}
			`;
		document.head.appendChild(style);
		
		var trs = document.querySelectorAll(table_selector + " tr");
		if (!trs || trs.length < 2) {
			return;
		}
		function ondragstart(ev) {
			ev.dataTransfer.setData("Text", ev.target.id);
		}
		function ondrop(ev) {
			var from = ev.dataTransfer.getData("Text");
			cbi_row_drop(from, this.id, store);
		}
		function ondragover(ev) {
			ev.preventDefault();
			ev.dataTransfer.dropEffect = "move";
		}
		
		// 上移一行
		function moveUp(id) {
			// 查找当前行的索引
			var trList = document.querySelectorAll(table_selector + " tr");
			var currentIndex = -1;
			for (var i = 0; i < trList.length; i++) {
				if (trList[i].id === id) {
					currentIndex = i;
					break;
				}
			}
			
			// 如果不是第一行数据行，则上移一行
			if (currentIndex > 1) {
				var prevRow = trList[currentIndex - 1];
				cbi_row_drop(id, prevRow.id, store);
			}
		}
		
		// 下移一行
		function moveDown(id) {
			// 查找当前行的索引
			var trList = document.querySelectorAll(table_selector + " tr");
			var currentIndex = -1;
			for (var i = 0; i < trList.length; i++) {
				if (trList[i].id === id) {
					currentIndex = i;
					break;
				}
			}
			
			// 如果不是最后一行，则下移一行
			if (currentIndex < trList.length - 1) {
				var nextRow = trList[currentIndex + 1];
				// 对于下移，我们需要将当前行插入到下一行的后面
				var nextNextRow = trList[currentIndex + 2];
				if (nextNextRow) {
					cbi_row_drop(id, nextNextRow.id, store, false);
				} else {
					// 如果是倒数第二行，移动到最后一行的后面
					cbi_row_drop(id, nextRow.id, store, true);
				}
			}
		}
		
		// 置顶
		function moveToTop(id) {
			var top = document.querySelectorAll(table_selector + " tr")[1];
			cbi_row_drop(id, top.id, store);
		}
		
		// 置底
		function moveToBottom(id) {
			//console.log('moveToBottom:', id);
			var trList = document.querySelectorAll(table_selector + " tr");
			var bottom = trList[trList.length - 1];
			cbi_row_drop(id, bottom.id, store, true);
		}
		
		for (let index = 1; index < trs.length; index++) {
			const el = trs[index];
			el.setAttribute("draggable", true);
			el.ondragstart = ondragstart;
			el.ondrop = ondrop;
			el.ondragover = ondragover;
			
			// 上移和下移按钮
			var upBtns = el.querySelectorAll(".cbi-button.cbi-button-up");
			if (upBtns && upBtns.length > 0) {
				upBtns.forEach(function (_el) {
					_el.onclick = function () {
						moveUp(el.id);
					};
				});
			}
			
			var downBtns = el.querySelectorAll(".cbi-button.cbi-button-down");
			if (downBtns && downBtns.length > 0) {
				downBtns.forEach(function (_el) {
					_el.onclick = function () {
						moveDown(el.id);
					};
				});
			}
			
			// 添加置顶和置底按钮
			var actionsCell = el.querySelector(".cbi-section-actions");
			if (actionsCell) {
				// 获取现有的按钮容器内的div
				var buttonDiv = actionsCell.querySelector("div");
        
				// 如果按钮容器内没有div，则创建一个
				if (!buttonDiv) {
					buttonDiv = document.createElement("div");
					actionsCell.appendChild(buttonDiv);
				}

				// 置顶按钮
				var toTopBtn = document.createElement("input");
				toTopBtn.className = "btn cbi-button cbi-button-top";
				toTopBtn.type = "button";
				toTopBtn.value = "<%:To Top%>";
				toTopBtn.title = "<%:To Top%>";
				toTopBtn.onclick = function () {
					moveToTop(el.id);
				};
				
				// 置底按钮
				var toBottomBtn = document.createElement("input");
				toBottomBtn.className = "btn cbi-button cbi-button-bottom";
				toBottomBtn.type = "button";
				toBottomBtn.value = "<%:To Bottom%>";
				toBottomBtn.title = "<%:To Bottom%>";
				toBottomBtn.onclick = function () {
					moveToBottom(el.id);
				};
				
				// 将置顶和置底按钮插入到单元格的开头
				buttonDiv.insertBefore(toBottomBtn, buttonDiv.firstChild);
				buttonDiv.insertBefore(toTopBtn, buttonDiv.firstChild);
			}
		}
	}

	// enable
	enableDragForTable(
		"#cbi-shadowsocksr-servers table",
		"cbi.sts.shadowsocksr.servers"
	);
	//]]>
</script>
