<%
local api = self.api
local appname = api.appname
-%>
<style>
 #cbi-<%=appname%>-socks .td.cbi-value-field > div {
	white-space: nowrap;
}
@media (max-width: 1152px) {
	 #cbi-<%=appname%>-socks .td.cbi-value-field > div {
		white-space: normal;
	}
}

.shunt-tab-hidden {
	display: none !important;
	visibility: hidden !important;
}
</style>
<script type="text/javascript">
	//<![CDATA[
	var shunt_list = JSON.parse('<%=self.shunt_list%>');

	function to_edit_node(btn) {
		if (!btn) return;
		const idReg = /^cbid\.<%=appname%>\..*node$/;
		let hidden_select = null;
		const container = btn.closest('#cbi-<%=appname%>-global') || btn.closest('#cbi-<%=appname%>-socks');
		if (!container) return null;
		const selects = container.querySelectorAll('select[id^="cbid.<%=appname%>."]');
		for (const sel of selects) {
			if ( idReg.test(sel.id) && getComputedStyle(sel).display === "none" && (sel.compareDocumentPosition(btn) & Node.DOCUMENT_POSITION_FOLLOWING)) {
				hidden_select = sel;
			}
		}
		if (!hidden_select) return;
		let node_select_value = hidden_select ? hidden_select.options[0].value : "";
		let to_url = '<%=api.url("node_config")%>/' + node_select_value;
		if (node_select_value.indexOf("Socks_") === 0) {
			to_url = '<%=api.url("socks_config")%>/' + node_select_value.substring("Socks_".length);
		}
		location.href = to_url;
	}

	function go() {
		var _status = document.getElementsByClassName('_status');
		for (var i = 0; i < _status.length; i++) {
			var id = _status[i].getAttribute("socks_id");
			XHR.get('<%=api.url("socks_status")%>', {
					index: i,
					id: id
				},
				function(x, result) {
					var index = result.index;
					var div = '';
					var div1 = '<font style="font-weight:bold;" color="green">✓</font>&nbsp';
					var div2 = '<font style="font-weight:bold;" color="red">X</font>&nbsp';

					if (result.socks_status) {
						div += div1;
					} else {
						div += div2;
					}
					if (result.use_http) {
						if (result.http_status) {
							div += div1;
						} else {
							div += div2;
						}
					}
					_status[index].innerHTML = div;
				}
			);
		}

		var global_id = null;
		var global = document.getElementById("cbi-<%=appname%>-global");
		if (global) {
			var node = global.getElementsByClassName("cbi-section-node")[0];
			var node_id = node.getAttribute("id");
			global_id = node_id;
			var all_node = node.querySelectorAll("[id]");
			//var reg1 = /^cbid\..*node\.main$/;
			var reg1 = /^cbid\..*\.(tcp_node|udp_node)\.main$/;

			for (var i = 0; i < all_node.length; i++) {
				var el = all_node[i];
				if (!reg1.test(el.id)) continue;

				var node_select = el;
				if (!node_select) continue;
				var cbid = el.id.replace(/\.main$/, "");
				var hidden_select = document.getElementById(cbid);
				var node_select_value = hidden_select ? hidden_select.options[0].value : "";
				if (!node_select_value || node_select_value === "" || node_select_value.indexOf("tcp") === 0) {
					continue;
				}

				var html = '<a href="#" onclick="return to_edit_node(this);"><%:Edit%></a>';

				var m = cbid.match(/\.(tcp|udp)_node$/);
				if (m && (m[1] === "tcp" || m[1] === "udp")) {
					html += '<a href="#" onclick="window.open(\'' + '<%=api.url("get_redir_log")%>?name=default&proto=' + m[1] + '\', \'_blank\')"><%:Log%></a>';
				}

				node_select.insertAdjacentHTML("beforeend",
					'<div class="node-actions" style="display:inline-flex; align-items:center; gap:4px; flex-wrap:wrap; margin-left:4px;">'
					+ html + '</div>'
				);
			}
		}

		var socks = document.getElementById("cbi-<%=appname%>-socks");
		if (socks) {
			var socks_enabled_dom = document.getElementById(global_id + "-socks_enabled");
			socks_enabled_dom.parentNode.removeChild(socks_enabled_dom);
			var descr = socks.getElementsByClassName("cbi-section-descr")[0];
			descr.outerHTML = socks_enabled_dom.outerHTML;
			rows = socks.getElementsByClassName("cbi-section-table-row");
			for (var i = 0; i < rows.length; i++) {
				try {
					var row = rows[i];
					var id = row.id;
					if (!id) continue;
					var dom_id = id + "-node";
					var cbid = dom_id.replace("cbi-", "cbid-").replace(new RegExp("-", 'g'), ".");
					dom_id = cbid + ".main";
					var node_select = document.getElementById(dom_id);
					if (!node_select) continue;

					var html = '<a href="#" onclick="return to_edit_node(this);"><%:Edit%></a>';
					html += '<a href="#" onclick="window.open(\'' + '<%=api.url("get_socks_log")%>?name=' + id.replace("cbi-<%=appname%>-", "") + '\', \'_blank\')"><%:Log%></a>';

					node_select.insertAdjacentHTML("afterend",
						'<div class="node-actions" style="display:inline-flex; align-items:center; gap:4px; flex-wrap:wrap; margin-left:4px;">'
						+ html + '</div>'
					);
				} catch(err) {
				}
			}
		}
	}

	(function () {
		let lastCount = 0;
		let stableTimes = 0;
		const STABLE_THRESHOLD = 5;
		function waitStable() {
			const list = document.querySelectorAll('[id^="cbid.<%=appname%>."][id$="node.main"]');
			const count = list.length;
			if (count === lastCount && count > 0) {
				stableTimes++;
			} else {
				stableTimes = 0;
				lastCount = count;
			}
			if (stableTimes >= STABLE_THRESHOLD) {
				go();
				return;
			}
			requestAnimationFrame(waitStable);
		}
		waitStable();
	})();

	(function () {
		const startTime = Date.now();
		const TIMEOUT = 3000;

		const waitForDnsSelect = () => {
			const dns_select = document.querySelector("select[id*='dns_shunt']");
			if (dns_select) {
				initDnsSelect(dns_select);
				return;
			}
			if (Date.now() - startTime >= TIMEOUT) {
				return;
			}
			requestAnimationFrame(waitForDnsSelect);
		};
		waitForDnsSelect();

		const initDnsSelect = (dns_select) => {
			if (dns_select.value === "chinadns-ng") {
				addLogLink(dns_select);
			}
			if (dns_select._dnsLogBinded) return;
			dns_select._dnsLogBinded = true;

			dns_select.addEventListener("change", () => {
				const existingLogLink = dns_select.parentElement.querySelector("a.dns-log-link");
				if (existingLogLink) {
					existingLogLink.remove();
				}
				if (dns_select.value === "chinadns-ng") {
					addLogLink(dns_select);
				}
			});
		};

		const addLogLink = (select) => {
			if (select.parentElement.querySelector("a.dns-log-link")) {
				return;
			}
			const logLink = document.createElement("a");
			logLink.innerHTML = "<%:Log%>";
			logLink.href = "#";
			logLink.className = "dns-log-link";
			logLink.style.marginLeft = "10px";
			logLink.setAttribute("onclick", "window.open('" + '<%=api.url("get_chinadns_log")%>' + "?flag=default', '_blank')");
			select.insertAdjacentElement("afterend", logLink);
		};
	})();

	document.addEventListener("DOMContentLoaded", function () {
		const hiddenSelect = document.getElementById("cbid.<%=appname%>.<%=self.global_cfgid%>.tcp_node");
		let o_val = hiddenSelect.value
		const o_hasItem = shunt_list.find(element => element.id == o_val);
		hiddenSelect.addEventListener("change", function(el){
			let new_val = el.target.value
			const new_hasItem = shunt_list.find(element => element.id == new_val);
			if (new_hasItem) {
				XHR.get('<%=api.url("update_node")%>', {
					id: "<%=self.global_cfgid%>",
					data: JSON.stringify({
						tcp_node: new_val
					})
				},
				function(x, data) {
					if (x && x.status == 200 && data.code == 1) {
						window.location.reload();
					}
					else {
						alert("<%:Error%>");
					}
				});
			} else {
				try {
					document.getElementById("tab.<%=appname%>.<%=self.global_cfgid%>.Shunt").classList.add('shunt-tab-hidden');
					document.getElementById("tab.<%=appname%>.<%=self.global_cfgid%>.Shunt").style.display = "none";
				} catch (error) {}
				try {
					document.querySelector('li[data-tab*="Shunt"]').classList.add('shunt-tab-hidden');
					document.querySelector('li[data-tab*="Shunt"]').style.display = "none";
				} catch (error) {}
			}
		});
		let shunt_taboption = document.getElementById("container.<%=appname%>.<%=self.global_cfgid%>.Shunt");
		if (shunt_taboption) {
			let shunt_option_list = document.getElementById("cbi-<%=appname%>-shunt_option_list");
			if (shunt_option_list) {
				shunt_taboption.appendChild(shunt_option_list);
			}
		}
	});
	//]]>
</script>
