<%#
 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 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 color="${col}">${(result.ping ? result.ping : "--") + " ms"}</font>`;
					if (result.socket) {
						port.innerHTML = '<font color="#249400">ok</font>';
					} else {
						port.innerHTML = '<font 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 = 2; 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;
			}
			`;
		document.head.appendChild(style);
		
		var trs = document.querySelectorAll(table_selector + " tr");
		if (!trs || trs.length.length < 3) {
			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 moveToTop(id) {
			var top = document.querySelectorAll(table_selector + " tr")[2];
			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 = 2; index < trs.length; index++) {
			const el = trs[index];
			el.setAttribute("draggable", true);
			el.ondragstart = ondragstart;
			el.ondrop = ondrop;
			el.ondragover = ondragover;
			// reset the behaviors of the btns
			var upBtns = el.querySelectorAll(".cbi-button.cbi-button-up");
			if (upBtns && upBtns.length > 0) {
				upBtns.forEach(function (_el) {
					_el.onclick = function () {
						moveToTop(el.id);
					};
				});
			}
			var downBtns = el.querySelectorAll(".cbi-button.cbi-button-down");
			if (downBtns && downBtns.length > 0) {
				downBtns.forEach(function (_el) {
					_el.onclick = function () {
						moveToBottom(el.id);
					};
				});
			}
		}
	}

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