<%+cbi/valueheader%>
<style type="text/css">
*{margin: 0;padding: 0;}

ul{
	list-style: none;
}

#tab{
	width: 100%;
	height: 100%;
	border: 1px solid #ddd;
	box-shadow: 0 0 2px #ddd;
	overflow: hidden;
}

#tab-header{
	min-height: 35px;
	text-align: center;
	position: relative;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
#tab-header ul{
	left: -1px;
	width: 100%;
	padding: unset !important;
	margin: unset !important;
}
#tab-header ul li{
	float: left;
	width: 160px;
	line-height: 35px;
	padding: 0 1px;
	border-right: 1px solid #dddddd;
	cursor: pointer;
}
#tab-header ul li a{
	float: unset !important;
	padding: unset !important;
	vertical-align: middle;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
#tab-header ul li.cbi-tab > a{
  font-weight: bolder;
  color: unset;
}
#tab-header ul li a:hover{
	color: orangered;
}
#tab-content .dom{
	display: none;
}
#tab-content .dom ul li{
  float: left;
  margin: 15px 10px;
  width: 225px;
}

.radio-button{
  width: fit-content;
	text-align: center;
	overflow: auto;
	margin: 10px auto;
	background-color: #d1d1d1;
	border-radius: 4px;
}

.radio-button input[type="radio"] {
	display: none;
}
   
.radio-button label {
	display: inline-block;
	padding: 4px 11px;
	font-size: 18px;
	color: white;
	cursor: pointer;
	border-radius: 4px;
}

.radio-button input[type="radio"]:checked+label {
	background-color: #1080c1;
}

</style>

<body>
	<div id="tab" class="cbi-section">
		<div id="tab-header" class="cbi-tabmenu">
			<ul class="cbi-tabmenu">
				<li name="tab-header" class="cbi-tab"><a><%:OpenClash Log%></a></li>
				<li name="tab-header"  class="cbi-tab-disabled"><a><%:Core Log%></a></li>
			</ul>
		</div>
		<div id="tab-content">
			<div class="dom" style="display: block;">
				<textarea id="cbid.openclash.config.clog" class="cbi-input-textarea" style="width: 100%;display:inline" data-update="change" rows="32" cols="60" readonly="readonly" ></textarea>
			</div>
			<div class="dom">
				<textarea id="core_log" class="cbi-input-textarea" style="width: 100%;display:inline" data-update="change" rows="32" cols="60" readonly="readonly" ></textarea>
				<div class="radio-button">
					<input type="radio" id="info" name="radios" value="info" checked onclick="return switch_log_level(this.value)"/>
					<label for="info">Info</label>
					<input type="radio" id="warning" name="radios" value="warning" onclick="return switch_log_level(this.value)"/>
					<label for="warning">Warning</label>
					<input type="radio" id="error" name="radios" value="error" onclick="return switch_log_level(this.value)"/>
					<label for="error">Error</label>
					<input type="radio" id="debug" name="radios" value="debug" onclick="return switch_log_level(this.value)"/>
					<label for="debug">Debug</label>
					<input type="radio" id="silent" name="radios" value="silent" onclick="return switch_log_level(this.value)"/>
					<label for="silent">Silent</label>
				</div>
			</div>
		</div>
	</div>

<fieldset style="text-align: center; width: 100%" class="cbi-section">
	<table>
		<tr>
			<td style="text-align: center; width: 25%">
				<input type="button" class="btn cbi-button cbi-button-apply" id="stop_refresh_button" value="<%:Stop Refresh Log%>" onclick=" return stop_refresh() "/>
			</td>
			<td style="text-align: center; width: 25%">
				<input type="button" class="btn cbi-button cbi-button-apply" id="start_refresh_button" value="<%:Start Refresh Log%>" onclick=" return start_refresh() "/>
			</td>
			<td style="text-align: center; width: 25%">
				<input type="button" class="btn cbi-button cbi-button-apply" id="del_log_button" value="<%:Clean Log%>" style=" display:inline;" onclick=" return del_log() " />
			</td>
			<td style="text-align: center; width: 25%">
				<input type="button" class="btn cbi-button cbi-button-apply" id="down_log_button" value="<%:Download Log%>" style=" display:inline;" onclick=" return download_log() " />
			</td>
		</tr>
	</table>
</fieldset>
</body>

<script type="text/javascript">//<![CDATA[
var r;
var s;
var log_len = 0;
var lv = document.getElementById('cbid.openclash.config.clog');
var cl = document.getElementById('core_log');

function get_log_level() {
	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "log_level")%>', null, function(x, status) {
	if (x && x.status == 200 && status.log_level != "") {
		var radio = document.getElementsByName("radios");
		for (i=0; i<radio.length; i++) {
			if (radio[i].value == status.log_level && ! radio[i].checked) {
				radio[i].checked = true;
			}
		}
	}
	});
	s=setTimeout("get_log_level()",5000);
};
	
function switch_log_level(value)
{
	clearTimeout(s);
	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "switch_log")%>', {log_level: value}, function(x, status) {
		if (x && x.status == 200) {
    	alert(' <%:Log Level%>: ' + value + ' <%:switching succeeded!%>');
    	get_log_level();
		}
		else {
			alert(' <%:Log Level%>: ' + value + ' <%:switching failed!%>');
			get_log_level();
		}
	});
};


function stop_refresh() {
	clearTimeout(r);
	return
};

function start_refresh() {
	clearTimeout(r);
	r=setTimeout("poll_log()",1000*2);
	return
};

function createAndDownloadFile(fileName, content) {
    var aTag = document.createElement('a');
    var blob = new Blob([content]);
    aTag.download = fileName;
    aTag.href = URL.createObjectURL(blob);
    aTag.click();
    URL.revokeObjectURL(blob);
};

function download_log(){
	var dt = new Date();
	var timestamp = dt.getFullYear()+"-"+(dt.getMonth()+1)+"-"+dt.getDate()+"-"+dt.getHours()+"-"+dt.getMinutes()+"-"+dt.getSeconds();
	createAndDownloadFile("OpenClash-"+timestamp+".log","<%:OpenClash Log%>:\n"+lv.innerHTML+"\n<%:Core Log%>:\n"+cl.innerHTML)
	return
};

function del_log() {
	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "del_log")%>',null,function(x, data){
		lv.innerHTML="";
		cl.innerHTML="";
		log_len = 0;
		oc_editor.setValue(lv.value);
		core_editor.setValue(cl.value);
		core_editor.refresh();
		oc_editor.refresh();
	});
	return
};

function p(s) {
	return s < 10 ? '0' + s: s;
};

function line_tolocal(str){
	var strt=new Array();
	var cstrt=new Array();
	var cn = 0;
	var sn = 0;
	str.trim().split('\n').forEach(function(v, i) {
		var regex = /"([^"]*)"/g;
		var res = regex.exec(v);
		if (res) {
			var dt = new Date(res[1]);
		}
		if (dt && dt != "Invalid Date"){
			if (v.indexOf("level=") != -1) {
				var log_info = v.substring(res[1].length + 7);
			}
			else {
				var log_info = v.substring(res[1].length + 2);
			}
			cstrt[cn]=dt.getFullYear()+"-"+p(dt.getMonth()+1)+"-"+p(dt.getDate())+" "+p(dt.getHours())+":"+p(dt.getMinutes())+":"+p(dt.getSeconds())+log_info;
			cn = cn + 1;
		}
		else{
			strt[sn]=v;
			sn = sn + 1;
		}
	})
	return [strt,cstrt]
};

function poll_log(){
XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "refresh_log")%>', {log_len: log_len},
	function(x, status) {
		if ( x && x.status == 200 ) {
			if (status && status.log != "" && lv && cl) {
				var log = line_tolocal(status.log);
				var lines = log[0];
				var clines = log[1];
				if (lines != "" || clines != "") {
					if (lines != "") {
						lv.innerHTML = lines.join('\n')+ (log_len != 0 ? '\n' : '') + lv.innerHTML;
						oc_editor.setValue(lv.value);
						oc_editor.refresh();
					}
					if (clines != "") {
						if (lines[0] != "..." && lines[lines.length-1] != "...") {
							cl.innerHTML = clines.join('\n') + (log_len != 0 ? '\n' : '') + cl.innerHTML;
						}
						else {
							cl.innerHTML = clines.join('\n') + (log_len != 0 ? '\n' : cl.innerHTML + '\n...');
						}
						core_editor.setValue(cl.value);
						core_editor.refresh();
					}
					log_len = status.len;
					//lv.innerHTML = x.responseText.split('\n').reverse().join('\n')+lv.innerHTML;
				}
			}
		}
	}
);
	r=setTimeout("poll_log()",1000*2);
};
 
window.onload = function(){
    var titles = document.getElementsByName('tab-header');
    var divs = document.getElementsByClassName('dom');
    if(titles.length != divs.length) return;
    for(var i=0; i<titles.length; i++){
        var li = titles[i];
        li.id = i;
        li.onclick = function(){
            for(var j=0; j<titles.length; j++){
                titles[j].className = 'cbi-tab-disabled';
                divs[j].style.display = 'none';
            }
            this.className = 'cbi-tab';
            divs[this.id].style.display = 'block';
        }
        li.onTouchStart = function(){
            for(var j=0; j<titles.length; j++){
                titles[j].className = 'cbi-tab-disabled';
                divs[j].style.display = 'none';
            }
            this.className = 'cbi-tab';
            divs[this.id].style.display = 'block';
        }
    }
    get_log_level();
    poll_log();
};
//]]>
</script>
<%+cbi/valuefooter%>
