<%#
 Copyright 2016-2017 Xingwang Liao <kuoruan@gmail.com>
 Licensed to the public under the Apache License 2.0.
-%>

<%
local kcp = require "luci.model.kcptun"
local dsp = require "luci.dispatcher"

local client_file = kcp.get_config_option("client_file")
local client_version = kcp.get_kcptun_version(client_file)
local luci_version = kcp.get_luci_version()
-%>

<fieldset class="cbi-section">
	<legend><%:Running Status%></legend>
	<table width="100%" cellspacing="10" id="_kcptun-status_table">
		<tr>
			<td width="33%"><%:Client Version%></td>
			<td>
				<% if client_version == "" then -%>
				<em><%:Invalid Client File.%></em>
				<% else -%>
				<%=pcdata(client_version)%>
				<%- end %>
			</td>
		</tr>
		<tr><td width="33%"><%:Client Status%></td><td id="_kcptun-client_status"><em><%:Collecting data...%></em></td></tr>
		<% if luci_version ~= "" then -%>
		<tr><td width="33%"><%:LuCI Version%></td><td><%=pcdata(luci_version)%></td></tr>
		<% end -%>
	</table>
</fieldset>

<script type="text/javascript">//<![CDATA[
	var client_status = document.getElementById('_kcptun-client_status');
	XHR.poll(5, '<%=dsp.build_url("admin/services/kcptun/status")%>', null,
		function(x, json) {
			if (x && x.status == 200) {
				client_status.innerHTML = json.client ? '<%:Running%>' : '<%:Not Running%>';
			}
		});

	function add_remove_page_notice(isAdd) {
		if (isAdd) {
			window.onbeforeunload = function(e) {
				var dialogText = '<%:Update in progress. Are you sure to close window?%>';
				e.returnValue = dialogText;
				return dialogText;
			};
		} else {
			window.onbeforeunload = null;
		}
	}

	function on_update_success(btn) {
		add_remove_page_notice(false);

		var success = '<%:Update Success.%>';

		if (btn) {
			btn.value = success;
			btn.placeholder = success;
			btn.disabled = true;
		}

		alert(success);

		window.setTimeout(function () {
			window.location.reload();
		}, 500);
	}

	function on_request_error(btn, json) {
		add_remove_page_notice(false);

		if (btn) {
			btn.disabled = false;
			btn.value = btn.placeholder;
		}

		if (json && json.error) {
			alert(json.error);
		}
	}

	function createVersionUrl(version, url) {
		var urlNode = '';
		if (url) {
			urlNode += '<a href="' + url + '" target="_blank">';
		}

		urlNode += '<em style="color:red;">' + version + '</em>';

		if (url) {
			urlNode += '</a>';
		}

		return urlNode;
	}

	var kcptun_info, luci_info;

	var token_str = '<%=token%>';
	var arch_select;

	function init_arch_select() {
		if (!arch_select) {
			arch_select = document.getElementById('cbid.kcptun.general.arch');

			arch_select.addEventListener('change', function() {
				kcptun_info = null;
				var check_kcptun_btn = document.getElementById('_kcptun-check_kcptun');
				var text = '<%:Check Kcptun Update%>';
				check_kcptun_btn.value = text;
				check_kcptun_btn.placeholder = text;
				check_kcptun_btn.setAttribute('onclick', 'check_update(\'kcptun\', this);');

				var detail = document.getElementById('_kcptun-check_kcptun-detail');
				detail.innerHTML = '';
			});
		}
	}

	function check_update(type, btn) {
		btn.disabled = true;
		btn.value = '<%:Processing...%>';

		init_arch_select();
		add_remove_page_notice(true);

		(new XHR()).get('<%=dsp.build_url("admin/services/kcptun/check")%>/' + type, {
			token: token_str,
			arch: arch_select ? arch_select.value : ""
		}, function(x, json) {
				if (x && x.status == 200) {
					var detailElm = document.getElementById(btn.id + '-detail');

					if (json.code == 0) {
						add_remove_page_notice(false);

						if (json.update) {
							eval(type + '_info = json');

							btn.disabled = false;
							btn.value = '<%:Click to Update%>';
							btn.placeholder = '<%:Click to Update%>';

							btn.setAttribute('onclick', 'do_' + type + '_update(this);');

							if (detailElm) {
								detailElm.innerHTML = createVersionUrl(json.version, json.url.html);
							}
						} else {
							btn.disabled = true;
							btn.value = '<%:No Update Found%>';

							if (detailElm) {
								detailElm.innerHTML = '';
							}
						}
					} else {
						if (detailElm && json.html_url) {
							detailElm.innerHTML = createVersionUrl(json.version, json.html_url)
						}

						on_request_error(btn, json);
					}
				} else {
					on_request_error(btn);
				}
			});
	}

	function do_kcptun_update(btn) {
		btn.disabled = true;
		btn.value = '<%:Downloading...%>';

		add_remove_page_notice(true);

		var kcptun_update_url = '<%=dsp.build_url("admin/services/kcptun/update/kcptun")%>';

		(new XHR()).get(kcptun_update_url, {
			token: token_str,
			url: kcptun_info ? kcptun_info.url.download : ''
		}, function (x, json) {
			if (x && x.status == 200) {
				if (json.code == 0) {
					btn.value = '<%:Extracting...%>';

					(new XHR()).get(kcptun_update_url, {
						token: token_str,
						task: "extract",
						file: json.file,
						subfix: kcptun_info ? kcptun_info.type : ''
					}, function (x, json) {
						if (x && x.status == 200) {
							if (json.code == 0) {
								btn.value = '<%:Moving...%>';

								(new XHR()).get(kcptun_update_url, {
									token: token_str,
									task: "move",
									file: json.file
								}, function (x, json) {
									if (x && x.status == 200) {
										if (json.code == 0) {
											on_update_success(btn);
										} else {
											on_request_error(btn, json);
										}
									} else {
										on_request_error(btn);
									}
								});
							} else {
								on_request_error(btn, json);
							}
						} else {
							on_request_error(btn);
						}
					});
				} else {
					on_request_error(btn, json);
				}
			} else {
				on_request_error(btn);
			}
		});
	}

	function do_luci_update(btn) {
		btn.disabled = true;
		btn.value = '<%:Processing...%>';

		add_remove_page_notice(true);

		var save_config = document.getElementById('cbid.kcptun.general.save_config');

		(new XHR()).get('<%=dsp.build_url("admin/services/kcptun/update/luci")%>', {
			token: token_str,
			url: luci_info ? luci_info.url.luci : '',
			save: save_config ? save_config.checked : false
		}, function(x, json) {
				btn.disabled = false;
				btn.value = btn.placeholder;
				if (x && x.status == 200) {
					if (json.code == 0) {
						on_update_success(btn);
					} else {
						on_request_error(btn, json);
					}
				} else {
					on_request_error(btn);
				}
			});
	}
//]]></script>
