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

ul{
	list-style: none;
}

.log_level{
	padding-top: 10px;
	height: 50px;
	text-align: center;
	overflow: auto;
	white-space: nowrap;
}

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

#tab-header{
	background-color: #F7F7F7;
	height: 33px;
	text-align: center;
	position: relative;
}
#tab-header ul{
	width: 500px;
	position: absolute;
	left: -1px;
}
#tab-header ul li{
	float: left;
	width: 120px;
	height: 33px;
	line-height: 33px;
	padding: 0 1px;
	border-bottom: 1px solid #dddddd;
	border-right: 1px solid #dddddd;
}
#tab-header ul li.selected{
  background-color: white;
  font-weight: bolder;
  border-bottom: 0;
  border-right: 1px solid #dddddd;
  padding: 0;
}
 
#tab-header ul li:hover{
	color: orangered;
}

#tab-content .dom{
	display: none;
}
 
#tab-content .dom ul li{
  float: left;
  /*background-color: red;*/
  margin: 15px 10px;
  width: 225px;
}

</style>

<body>
	<div id="tab">
		<div id="tab-header">
			<ul>
				<li name="tab-header" class="selected"><%:OpenClash Log%></li>
				<li name="tab-header"><%:Core Log%></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="log_level">&nbsp;&nbsp;<%:Log Level%>:&nbsp;
					<select id="log_level">
						<option value="info"><%:Info Mode%></option>
						<option value="warning"><%:Warning Mode%></option>
						<option value="error"><%:Error Mode%></option>
						<option value="debug"><%:Debug Mode%></option>
						<option value="silent"><%:Silent Mode%></option>
					</select>&nbsp;&nbsp;
					<input type="button" class="btn cbi-button cbi-button-apply" value="<%:Switch Log Level%>" onclick="return switch_log_level(this)" />
					&nbsp;
				</div>
		</div>
	</div>
</div>

<fieldset class="cbi-section">
	<table width="100%">
		<tr>
			<td width="25%" align="center">
				<input type="button" class="btn cbi-button cbi-button-apply" id="stop_refresh_button" value="<%:Stop Refresh Log%>" onclick=" return stop_refresh() "/>
			</td>
			<td width="25%" align="center">
				<input type="button" class="btn cbi-button cbi-button-apply" id="start_refresh_button" value="<%:Start Refresh Log%>" onclick=" return start_refresh() "/>
			</td>
			<td width="25%" align="center">
				<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 width="25%" align="center">
				<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');
var log_level = document.getElementById('log_level');

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 != "") {
   	log_level.value = status.log_level;
   	clearTimeout(s);
	}
	else {
		s=setTimeout("get_log_level()",2000);
	}
});
}

	
function switch_log_level(btn)
{
	btn.disabled = true;
	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "switch_log")%>', {log_level: log_level.value}, function(x, status) {
		if (x && x.status == 200) {
   		btn.disabled = false;
    	alert(' <%:Log Level%>: ' + log_level.value + ' <%:switching succeeded!%>')
		}
		else {
			alert(' <%:Log Level%>: ' + log_level.value + ' <%:switching failed!%>')
		}
	});
	btn.disabled = false;
	return false;
}

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].match(/\+08\:00/)? res[1].replace("+08:00", "Z") : res[1]);
		}
		if (dt && dt != "Invalid Date"){
		  cstrt[cn]=dt.getFullYear()+"-"+p(dt.getMonth()+1)+"-"+p(dt.getDate())+" "+p(dt.getHours())+":"+p(dt.getMinutes())+":"+p(dt.getSeconds())+v.substring(res[1].length + 7);
			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 = '';
                divs[j].style.display = 'none';
            }
            this.className = 'selected';
            divs[this.id].style.display = 'block';
        }
        li.onTouchStart = function(){
            for(var j=0; j<titles.length; j++){
                titles[j].className = '';
                divs[j].style.display = 'none';
            }
            this.className = 'selected';
            divs[this.id].style.display = 'block';
        }
    }
    get_log_level();
    poll_log();
}
//]]>
</script>
<%+cbi/valuefooter%>
