<%#
 Copyright 2018-2019 Lienol <lawlienol@gmail.com>
 Licensed to the public under the Apache License 2.0.
-%>
<%
local dsp=require "luci.dispatcher"
-%>
<script type="text/javascript">
	//<![CDATA[
	window.addEventListener('load',function(){
	const doms=document.getElementsByClassName('pingtime');
	const ports=document.getElementsByClassName("socket-connected")
	const xhr=(index) =>{
		return new Promise((res) =>{
			const dom=doms[index];
			const port=ports[index];
			if (!dom) res()
			port.innerHTML='<font style=\"color:#0072c3\"><%:connecting%></font>';
			XHR.get('<%=dsp.build_url("admin/services/bypass/ping")%>',{
				index,
				domain: dom.getAttribute("hint"),
				port: port.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';
					port.innerHTML='<font style=\"color:#249400\"><%:ok%></font>'
				}else{
					port.innerHTML='<font style=\"color:#ff0000\"><%:fail%></font>'
				}
				dom.innerHTML =`<font style=\"${col}\">${(result.ping?result.ping:"--")+" ms"}</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_selecter,store){
		var trs=document.querySelectorAll(table_selecter + " 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_selecter + " tr")[2];
			cbi_row_drop(id,top.id,store);
		}

		function moveToBottom(id){
			console.log('moveToBottom:',id);
			var trList=document.querySelectorAll(table_selecter + " 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-bypass-servers table",
		"cbi.sts.bypass.servers"
	);

	function _cbi_row_top(id) {
		var dom = document.getElementById("cbi-bypass-" + id);
		if (dom) {
			var trs = document.getElementById("cbi-bypass-servers").getElementsByClassName("cbi-section-table-row");
			if (trs && trs.length > 0) {
				for (var i = 0; i < trs.length; i++) {
					var up = dom.getElementsByClassName("cbi-button-up");
					if (up) {
						cbi_row_swap(up[0], true, 'cbi.sts.bypass.servers');
					}
				}
			}
		}
	}

	var edit_btn = document.getElementById("cbi-bypass-servers").getElementsByClassName("cbi-button cbi-button-edit");
	for (var i = 0; i < edit_btn.length; i++) {
		try {
			var onclick_str = edit_btn[i].getAttribute("onclick");
			var id = onclick_str.substring(onclick_str.lastIndexOf('/') + 1, onclick_str.length - 1);
			var td = edit_btn[i].parentNode;
			var new_div = "";
			new_div += '<input class="cbi-button" type="button" value="<%:To Top%>" onclick="_cbi_row_top(\'' + id + '\')"/>&nbsp;&nbsp;';
			td.innerHTML = new_div + td.innerHTML;
		}
		catch(err) {
			console.error(err);
		}
	}
</script>
