<%
    local fs = require "luci.openclash"
    local plugin_version = fs.oc_version()
%>
<script src="/luci-static/resources/openclash/js/oc-icons.js?v=<%=plugin_version%>"></script>
<fieldset class="cbi-section">
	<table width="100%">
		<tr>
			<td width="100%" colspan="6">
				<p align="center" id="update_tip" class="oc" style="background-color: unset;">
					<b style="color: var(--info-color);"><%:Note: if the update fails, you can manually download and upload%></b>
				</p>
			</td>
		</tr>
		<tr>
			<td width="16.6%" align="right"><%:Compiled Version%></td>
			<td width="16.6%" align="left">
				<select class="cbi-input-select oc-arch-select" name="CORE_VERSION" id="CORE_VERSION">
				</select>
			</td>
			<td width="16.6%" align="right"><%:Release Branch%></td>
			<td width="16.6%" align="left">
				<select class="cbi-input-select" name="RELEASE_BRANCH" id="RELEASE_BRANCH">
					<option value="master">Master</option>
					<option value="dev">Developer</option>
				</select>
			</td>
			<td width="16.6%" align="right"><%:Smart Core%> 
				<a href="javascript:void(0);" onclick="window.open('https://github.com/vernesong/mihomo/releases', '_blank');" style="color: #0066cc; text-decoration: none;" title="<%:View core infos that support smart group%>">
					<svg width="12" height="12"><use href="#oc-icon-help"/></svg>
				</a>
			</td>
			<td width="16.6%" align="left">
				<select class="cbi-input-select" name="SMART_ENABLE" id="SMART_ENABLE">
					<option value="0"><%:Disabled%></option>
					<option value="1"><%:Enable%></option>
				</select>
			</td>
		</tr>
	</table>
</fieldset>
<fieldset class="cbi-section">
	<table width="100%">
		<tr>
			<td width="100%" colspan="4">
				<p align="center">
					<b><%:Core Update%></b>
				</p>
			</td>
		</tr>
		<tr>
			<td width="25%"><%:CPU Architecture%></td><td width="25%" align="left" id="CPU_MODEL"><%:Collecting data...%></td>
			<td width="25%"><%:Last Check Update%></td><td width="25%" align="left" id="CHECKTIME"><%:Collecting data...%></td>
		</tr>
		<tr>
			<td width="100%" colspan="4">
				<p align="center">
					<b><%:Core path:%>/etc/openclash/core/clash_meta</b>
				</p>
			</td>
		</tr>
		<tr><td width="25%">[Meta] <%:Current Core%></td><td width="25%" align="left" id="CORE_META_CV"><%:Collecting data...%></td><td width="25%">[Meta] <%:Latest Core%></td><td width="25%" align="left" id="CORE_META_LV"><%:Collecting data...%></td></tr>
		<tr><td width="25%"><%:Update Core%></td><td width="25%" align="left" id="core_meta_up"><%:Collecting data...%></td><td width="25%"><%:Download Latest Core%></td><td width="25%" align="left" id="ma_core_meta_up"><%:Collecting data...%></td></tr>
	</table>
</fieldset>
<fieldset class="cbi-section">
	<table width="100%">
		<tr>
			<td width="100%" colspan="4">
				<p align="center">
					<b><%:Client Update%></b>
				</p>
			</td>
		</tr>
		<tr><td width="25%"><%:Current Client%></td><td width="25%" align="left" id="OP_CV"><%:Collecting data...%></td><td width="25%"><%:Latest Client%></td><td width="25%" align="left" id="OP_LV"><%:Collecting data...%></td></tr>
		<tr><td width="25%"><%:Update Client%></td><td width="25%" align="left" id="op_up"><%:Collecting data...%></td><td width="25%"><%:Download Latest Client%></td><td width="25%" align="left" id="ma_op_up"><%:Collecting data...%></td></tr>
	</table>
</fieldset>
<fieldset class="cbi-section">
	<table width="100%">
		<tr>
			<td width="25%" align="center">
				<div style="display: inline-block; white-space: nowrap;">
					<select class="cbi-input-select" name="BACKUP_SELECT" id="BACKUP_SELECT">
						<option value="backup"><%:Backup File%></option>
						<option value="backup_ex_core"><%:Backup Exclude Cores%></option>
						<option value="backup_only_core"><%:Backup Core%></option>
						<option value="backup_only_config"><%:Backup Config%></option>
						<option value="backup_only_rule"><%:Backup Rule Provider%></option>
						<option value="backup_only_proxy"><%:Backup Proxy Provider%></option>
					</select>
					<span id="backup">
						<%:Collecting data...%>
					</span>
				</div>
			</td>
			<td width="25%" align="center" id="restore">
				<%:Collecting data...%>
			</td>
			<td width="25%" align="center" id="remove_core">
				<%:Collecting data...%>
			</td>
			<td width="25%" align="center" id="one_key_update_cdn">
				<%:Collecting data...%>
			</td>
		</tr>
	</table>
</fieldset>

<%+openclash/common%>
<script type="text/javascript">//<![CDATA[
	var core_version = document.getElementById('CORE_VERSION');
 	var checktime = document.getElementById('CHECKTIME');
	var cpu_model = document.getElementById('CPU_MODEL');
	var core_meta_cv = document.getElementById('CORE_META_CV');
	var core_meta_lv = document.getElementById('CORE_META_LV');
	var op_cv = document.getElementById('OP_CV');
	var op_lv = document.getElementById('OP_LV');
	var core_meta_up = document.getElementById('core_meta_up');
	var op_up = document.getElementById('op_up');
	var update_tip = document.getElementById('update_tip');
	var ma_core_meta_up = document.getElementById('ma_core_meta_up');
	var ma_op_up = document.getElementById('ma_op_up');
	var restore = document.getElementById('restore');
	var backup = document.getElementById('backup');
	var backup_select = document.getElementById('BACKUP_SELECT');
	var one_key_update_cdn = document.getElementById('one_key_update_cdn');
	var remove_core = document.getElementById('remove_core');
	var release_branch = document.getElementById('RELEASE_BRANCH');
	var smart_enable = document.getElementById('SMART_ENABLE');
	core_meta_up.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reload" value="<%:Check And Update%>" onclick="return core_update(this,\'Meta\')"/>';
	op_up.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reload" value="<%:Check And Update%>" onclick="return op_update(this)"/>';
	ma_core_meta_up.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reload" value="<%:Download%>" onclick="return ma_core_update(this,\'Meta\')"/>';
	ma_op_up.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reload" value="<%:Download%>" onclick="return ma_op_update(this)"/>';
	restore.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Restore Default%>" onclick="return restore_config(this)"/>';
	one_key_update_cdn.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Check Update%>" onclick="return all_one_key_update_cdn(this)"/>';
	remove_core.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Remove Core%>" onclick="return remove_all_core(this)"/>';
	backup.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Backup File%>" onclick="return backup_file(this)"/>';

	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "update_info")%>', null, function(x, status) {
		if ( x && x.status == 200 ) {
			if ( status.corever && status.corever != "0" && status.corever != "" ) {
					core_version.value = status.corever;
			}
			else {
					core_version.value = "0";
			}
			if ( status.release_branch && status.release_branch != "" ) {
					release_branch.value = status.release_branch;
			}
			else {
					release_branch.value = "master";
			}
			if ( status.smart_enable && status.smart_enable != "" ) {
				smart_enable.value = status.smart_enable;
			}
			else {
				smart_enable.value = "0";
			}
		}
		else {
			core_version.value = "0";
			release_branch.value = "master";
			smart_enable.value = "0";
		}
	});

	XHR.poll(300, '<%=luci.dispatcher.build_url("admin", "services", "openclash", "get_last_version")%>', null, function(x, status) {
	});
	
	function updateStatus(x, status) {
		if ( x && x.status == 200 ) {
			cpu_model.innerHTML = status.coremodel ? "<b style=color:green>"+status.coremodel+"</b>" : "<b style=color:red><%:Model Not Found%></b>";

			if ( status.upchecktime != "1" ) {
				checktime.innerHTML = "<b style=color:green>"+status.upchecktime+"</b>";
			} else {
				checktime.innerHTML = "<b style=color:red><%:Check Failed%></b>";
			}
			if ( status.coremetacv == "0" ) {
				core_meta_cv.innerHTML = "<b style=color:red><%:Unknown%></b>";
			} else {
				core_meta_cv.innerHTML = "<b style=color:green>"+status.coremetacv+"</b>";
			}

			var coremetalvis = status.corelv;

			if (coremetalvis != status.coremetacv && coremetalvis != "" && coremetalvis != "loading...") {
				core_meta_lv.innerHTML = "<b style=color:green>"+coremetalvis+" <%:<New>%></b>";
			} else if (coremetalvis != "" && coremetalvis == status.coremetacv && coremetalvis != "loading...") {
				core_meta_lv.innerHTML = "<b style=color:green>"+coremetalvis+"</b>";
			} else if (coremetalvis == "loading...") {
				core_meta_lv.innerHTML = "<b style=color:green><%:Getting Last Version...%></b>";
			} else {
				core_meta_lv.innerHTML = "<b style=color:red><%:Unknown%></b>";
			}

			var oplv = status.oplv;
			op_cv.innerHTML = status.opcv != "0" ? "<b style=color:green>"+status.opcv+"</b>" : "<b style=color:red><%:Unknown%></b>";

			if (oplv != "" && oplv != "loading..." && status.opcv != "0") {
				function compareVersions(v1, v2) {
					var ver1 = v1.replace(/^v/, '').split('.');
					var ver2 = v2.replace(/^v/, '').split('.');

					var maxLen = Math.max(ver1.length, ver2.length);
					while (ver1.length < maxLen) ver1.push('0');
					while (ver2.length < maxLen) ver2.push('0');

					for (var i = 0; i < maxLen; i++) {
							var num1 = parseInt(ver1[i], 10);
							var num2 = parseInt(ver2[i], 10);
							if (num1 > num2) return 1;
							if (num1 < num2) return -1;
					}
					return 0;
				}

				if (compareVersions(oplv, status.opcv) > 0) {
					op_lv.innerHTML = "<b style=color:green>"+oplv+" <%:<New>%></b>";
				} else {
					op_lv.innerHTML = "<b style=color:green>"+oplv+"</b>";
				}
			} else if (oplv != "" && oplv != "loading...") {
				op_lv.innerHTML = "<b style=color:green>"+oplv+"</b>";
			} else if (oplv == "loading...") {
				op_lv.innerHTML = "<b style=color:green><%:Getting Last Version...%></b>";
			} else {
				op_lv.innerHTML = "<b style=color:red><%:Unknown%></b>";
			}
		}
	}

	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "update")%>', null, updateStatus);

	XHR.poll(10, '<%=luci.dispatcher.build_url("admin", "services", "openclash", "update")%>', null, updateStatus);

	function handleStartLog(x, status) {
		if ( x && x.status == 200 ) {
			if ( status.startlog == "\n" || status.startlog == "" || status.startlog == "##FINISH##\n" ) {
				var rdmdl = Math.floor(Math.random()*3)+1;
				if(rdmdl == 1) {
					update_tip.innerHTML = '<b style=color:var(--info-color)><%:Note: if the update fails, you can manually download and upload%></b>';
				}
				else if(rdmdl == 2) {
					update_tip.innerHTML = '<b style=color:var(--info-color)><%:Note: the client may not support update, because the firmware with squashfs format will not release flash space after updating%></b>';
				}
				else if(rdmdl == 3) {
					update_tip.innerHTML = '<b style=color:var(--info-color)><%:Note: options will auto-save when you click to update or download%></b>';
				}
			} else if ( status.startlog.match("level=fatal")) {
				XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "del_start_log")%>', null, function(x) {});
				if ( status.startlog.match("level=fatal") ) {
					alert('<%:OpenClash Start Failed%> :\n\n' + status.startlog.split('msg=')[1]);
				}
			} else if ( status.startlog != "\n" && status.startlog != "" && status.startlog != "##FINISH##\n" ) {
				for (var levelKey in window.levelTranslations) {
					var translatedText = '[' + window.levelTranslations[levelKey] + ']';
					if (status.startlog.match(translatedText)) {
						update_tip.innerHTML = '<b style=color:var(--' + levelKey + '-color)>' + status.startlog + '</b>';
						return;
					}
				}
				update_tip.innerHTML = '<b style=color:var(--info-color)>' + status.startlog + '</b>';
			}
		}
	}

	XHR.poll(3, '<%=luci.dispatcher.build_url("admin", "services", "openclash", "startlog")%>', null, handleStartLog);
	
	function core_update(btn,type) {
		var v = core_version.value;
		var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
			if (x && x.status == 200) {
				XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "coreupdate")%>', {core_type: type}, function(x, status) {
					btn.value = '<%:Check And Update%>';
					btn.disabled = false;
					return false;
				});
			}
		});
	}

	function op_update(btn) {
		var v = core_version.value;
		var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
			if (x && x.status == 200) {
				XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "opupdate")%>', null, function(x, status) {
					btn.value = '<%:Check And Update%>';
					btn.disabled = false;
					return false;
				});
			}
		});
	}

	function ma_core_update(btn,type) {
		var v = core_version.value;
		var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
			if (x && x.status == 200) {
				btn.value = '<%:Download%>';
				btn.disabled = false;
				XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "update_ma")%>', status.corever, function(x, status) {
					if ( x && x.status == 200 ) {
						if ( status.corever != "0" ) {
							if (status.oix_core) {
								if (status.corelv && status.corelv != "" && status.corelv != "loading...") {
									url4='https://github.com/vernesong/mihomo-oix/releases/download/Pre-Alpha/mihomo-'+status.corever+'-'+status.corelv+'.gz';
									window.location.href=url4;
								}
							} else if (type == "Meta") {
								if (s == "1") {
									url4='https://raw.githubusercontent.com/vernesong/OpenClash/core/'+r+'/smart/clash-'+status.corever+'.tar.gz';
									window.location.href=url4;
								} else {
									url4='https://raw.githubusercontent.com/vernesong/OpenClash/core/'+r+'/meta/clash-'+status.corever+'.tar.gz';
									window.location.href=url4;
								}
							}
						} else {
							alert('<%:No Compiled Version is Selected, Please Select on The Top and Try Again!%>')
						}
					}
				});
				return false;
			}
		});
	}

	function ma_op_update(btn) {
		btn.value = '<%:Download%>';
		btn.disabled = false;
		var v = core_version.value;
		var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
			if (x && x.status == 200) {
				XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "update_ma")%>', status.oplv, function(x, status) {
					if ( x && x.status == 200 ) {
						var oplv = status.oplv.substring(status.oplv.indexOf("v") + 1);
						if ( oplv != "" && oplv != "loading..." ) {
							if (status.pkg_type == "apk") {
								url2='https://raw.githubusercontent.com/vernesong/OpenClash/package/'+r+'/luci-app-openclash-'+oplv+'.apk';
							} else {
								url2='https://raw.githubusercontent.com/vernesong/OpenClash/package/'+r+'/luci-app-openclash_'+oplv+'_all.ipk';
							}
							window.location.href=url2;
						} else {
							alert('<%:Failed to get the latest version. Please try again later!%>')
						}
					}
				});
			}
		});
		return false; 
	}

	function remove_all_core(btn) {
		btn.value = '<%:Remove Core%>';
		btn.disabled = true;
		var r = confirm("<%:Are you sure want to remove all core files?%>")
		if (r == true) {
			XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "remove_all_core")%>', null, function(x, status) {
				if ( x && x.status == 200 ) {
					alert('<%:Remove succeeded!%>')
				} else {
					alert('<%:Remove failed!%>')
				}
			});
		}
		btn.disabled = false;
		return false; 
	}

	function backup_file(btn) {
		btn.value = '<%:Backup File%>';
		btn.disabled = true;
		window.location.href=backup_select.value;
		btn.disabled = false;
		return false; 
	}

	function all_one_key_update_cdn(btn) {
		var v = core_version.value;
		var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
			if (x && x.status == 200) {
				btn.value = '<%:Check Update%>';
				btn.disabled = false;
				return select_git_cdn("one_key_update");
			}
		});
	}

//]]></script>
