<%
local api = require "luci.passwall.api"
-%>
<script type="text/javascript">
	//<![CDATA[
	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-<%=api.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$/;

			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.indexOf("_default") === 0 || node_select_value.indexOf("_direct") === 0 || node_select_value.indexOf("_blackhole") === 0) {
					continue;
				}

				var 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);
				}
				var html = '<a href="#" onclick="location.href=\'' + to_url + '\'"><%: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-<%=api.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 hidden_select = document.getElementById(cbid);;
					var node_select_value = hidden_select ? hidden_select.options[0].value : "";
					if (node_select_value && node_select_value != "") {
						var to_url = '<%=api.url("node_config")%>/' + node_select_value;
						var html = '<a href="#" onclick="location.href=\'' + to_url + '\'"><%:Edit%></a>';
						html += '<a href="#" onclick="window.open(\'' + '<%=api.url("get_socks_log")%>?name=' + id.replace("cbi-passwall-", "") + '\', \'_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.<%=api.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);
		};
	})();
	//]]>
</script>
