<%+cbi/valueheader%>
<script type="text/javascript">
//<![CDATA[
function padright(str, cnt, pad) {
	return str + Array(cnt + 1).join(pad);
}

function b64EncodeUnicode(str) {
	return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
		return String.fromCharCode('0x' + p1);
	}));
}

function b64encutf8safe(str) {
	return b64EncodeUnicode(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, '');
}

function b64DecodeUnicode(str) {
	return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) {
		return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
	}).join(''));
}

function b64decutf8safe(str) {
	var l;
	str = str.replace(/-/g, "+").replace(/_/g, "/");
	l = str.length;
	l = (4 - l % 4) % 4;
	if (l) str = padright(str, l, "=");
	return b64DecodeUnicode(str);
}

function b64encsafe(str) {
	return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, '')
}

function b64decsafe(str) {
	var l;
	str = str.replace(/-/g, "+").replace(/_/g, "/");
	l = str.length;
	l = (4 - l % 4) % 4;
	if (l) str = padright(str, l, "=");
	return atob(str);
}

function dictvalue(d, key) {
	var v = d[key];
	if (typeof (v) == 'undefined' || v == '') return '';
	return b64decsafe(v);
}

function export_ssr_url(btn, urlname, sid) {
	var s = document.getElementById(urlname + '-status');
	if (!s) return false;
	var v_server = document.getElementsByName('cbid.openclash.' + sid + '.server')[0];
	var v_port = document.getElementsByName('cbid.openclash.' + sid + '.port')[0];
	var v_protocol = document.getElementsByName('cbid.openclash.' + sid + '.protocol')[0];
	var v_method = document.getElementsByName('cbid.openclash.' + sid + '.cipher_ssr')[0];
	var v_obfs = document.getElementsByName('cbid.openclash.' + sid + '.obfs_ssr')[0];
	var v_password = document.getElementsByName('cbid.openclash.' + sid + '.password')[0];
	var v_obfs_param = document.getElementsByName('cbid.openclash.' + sid + '.obfs_param')[0];
	var v_protocol_param = document.getElementsByName('cbid.openclash.' + sid + '.protocol_param')[0];
	var v_alias = document.getElementsByName('cbid.openclash.' + sid + '.name')[0];
	var ssr_str = v_server.value + ":" + v_port.value + ":" + v_protocol.value + ":" + v_method.value + ":" + v_obfs.value + ":" + b64encsafe(v_password.value) + "/?obfsparam=" + b64encsafe(v_obfs_param.value) + "&protoparam=" + b64encsafe(v_protocol_param.value) + "&remarks=" + b64encutf8safe(v_alias.value);
	var textarea = document.createElement("textarea");
	textarea.textContent = "ssr://" + b64encsafe(ssr_str);
	textarea.style.position = "fixed";
	document.body.appendChild(textarea);
	textarea.select();
	try {
		document.execCommand("copy"); // Security exception may be thrown by some browsers.
		s.innerHTML = "<font color='green'><%:Copy SSR to clipboard successfully.%></font>";
	} catch (ex) {
		s.innerHTML = "<font color='red'><%:Unable to copy SSR to clipboard.%></font>";
	} finally {
		document.body.removeChild(textarea);
	}
	return false;
}

function import_ssr_url(btn, urlname, sid) {
		var s = document.getElementById(urlname + '-status');
		if (!s) return false;
		var ssrurl = prompt("<%:Paste sharing link here%>", "");
		if (ssrurl == null || ssrurl == "") {
			s.innerHTML = "<font color='red'><%:User cancelled.%></font>";
			return false;
		}
		s.innerHTML = "";
		//var ssu = ssrurl.match(/ssr:\/\/([A-Za-z0-9_-]+)/i);
		var ssu = ssrurl.split('://');
		//console.log(ssu.length);
		var event = document.createEvent("HTMLEvents");
		event.initEvent("change", true, true);
		switch (ssu[0]) {
		case "ss":
			var url0, param = "";
			var sipIndex = ssu[1].indexOf("@");
			var ploc = ssu[1].indexOf("#");
			if (ploc > 0) {
				url0 = ssu[1].substr(0, ploc);
				param = ssu[1].substr(ploc + 1);
			} else {
				url0 = ssu[1];
			}
			if (sipIndex != -1) {
				// SIP002
				var userInfo = b64decsafe(url0.substr(0, sipIndex));
				var temp = url0.substr(sipIndex + 1).split("/?");
				var serverInfo = temp[0].split(":");
				var server = serverInfo[0];
				var port = serverInfo[1];
				var method, password, plugin, pluginOpts, pluginObfs, pluginObfsHost, pluginObfsPath, pluginObfsHeaders;
				if (temp[1]) {
					var pluginInfo = decodeURIComponent(temp[1]);
					var pluginIndex = pluginInfo.indexOf(";");
					var pluginNameInfo = pluginInfo.substr(0, pluginIndex);
					plugin = pluginNameInfo.substr(pluginNameInfo.indexOf("=") + 1);
					pluginOpts = pluginInfo.substr(pluginIndex + 1);
					if (pluginOpts.indexOf("obfs=") != -1) {
						pluginObfs = pluginOpts.split("obfs=")[1].split(";")[0];
						if (pluginObfs == "ws") {
							   pluginObfs = "websocket"
							}
						if (pluginOpts.indexOf("obfs-host=") != -1) {
							pluginObfsHost = pluginOpts.split("obfs-host=")[1].split("&group=")[0] || pluginOpts.split("obfs-host=")[1].split(";")[0];
							}
						if (pluginOpts.indexOf("path=") != -1) {
							pluginObfsPath = pluginOpts.split("path=")[1].split(";")[0];
							}
						if (pluginOpts.indexOf("headers=") != -1) {
							pluginObfsHeaders = pluginOpts.split("headers=")[1].split(";")[0];
							}
					}
				}
				var userInfoSplitIndex = userInfo.indexOf(":");
				if (userInfoSplitIndex != -1) {
					method = userInfo.substr(0, userInfoSplitIndex);
					password = userInfo.substr(userInfoSplitIndex + 1);
				}
				document.getElementsByName('cbid.openclash.' + sid + '.type')[0].value = ssu[0];
				document.getElementsByName('cbid.openclash.' + sid + '.type')[0].dispatchEvent(event);
				document.getElementsByName('cbid.openclash.' + sid + '.server')[0].value = server;
				document.getElementsByName('cbid.openclash.' + sid + '.port')[0].value = port;
				document.getElementsByName('cbid.openclash.' + sid + '.password')[0].value = password || "";
				document.getElementsByName('cbid.openclash.' + sid + '.cipher')[0].value = method || "";
				document.getElementsByName('cbid.openclash.' + sid + '.obfs')[0].value = pluginObfs || "none";
				document.getElementsByName('cbid.openclash.' + sid + '.obfs')[0].dispatchEvent(event);
				if (plugin != undefined) {
					document.getElementsByName('cbid.openclash.' + sid + '.host')[0].value = pluginObfsHost || "";
					if (pluginObfs == "websocket") {
						document.getElementsByName('cbid.openclash.' + sid + '.custom')[0].value = pluginObfsHeaders || "";
						document.getElementsByName('cbid.openclash.' + sid + '.path')[0].value = pluginObfsPath || "";
					}
				}
				if (param != undefined) {
					document.getElementsByName('cbid.openclash.' + sid + '.name')[0].value = decodeURI(param);
				}
				s.innerHTML = "<font color='green'><%:Import configuration information successfully.%></font>";
			} else {
				var sstr = b64decsafe(url0);
				document.getElementsByName('cbid.openclash.' + sid + '.type')[0].value = ssu[0];
				document.getElementsByName('cbid.openclash.' + sid + '.type')[0].dispatchEvent(event);
				var team = sstr.split('@');
				var part1 = team[0].split(':');
				var part2 = team[1].split(':');
				document.getElementsByName('cbid.openclash.' + sid + '.server')[0].value = part2[0];
				document.getElementsByName('cbid.openclash.' + sid + '.port')[0].value = part2[1];
				document.getElementsByName('cbid.openclash.' + sid + '.password')[0].value = part1[1];
				document.getElementsByName('cbid.openclash.' + sid + '.cipher')[0].value = part1[0];
				if (param != undefined) {
					document.getElementsByName('cbid.openclash.' + sid + '.name')[0].value = decodeURI(param);
				}
				s.innerHTML = "<font color='green'><%:Import configuration information successfully.%></font>";
			}
			return false;
		case "ssr":
			var sstr = b64decsafe(ssu[1]);
			var ploc = sstr.indexOf("/?");
			document.getElementsByName('cbid.openclash.' + sid + '.type')[0].value = ssu[0];
			document.getElementsByName('cbid.openclash.' + sid + '.type')[0].dispatchEvent(event);
			var url0, param = "";
			if (ploc > 0) {
				url0 = sstr.substr(0, ploc);
				param = sstr.substr(ploc + 2);
			}
			var ssm = url0.match(/^(.+):([^:]+):([^:]*):([^:]+):([^:]*):([^:]+)/);
			if (!ssm || ssm.length < 7) return false;
			var pdict = {};
			if (param.length > 2) {
				var a = param.split('&');
				for (var i = 0; i < a.length; i++) {
					var b = a[i].split('=');
					pdict[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
				}
			}
			document.getElementsByName('cbid.openclash.' + sid + '.server')[0].value = ssm[1];
			document.getElementsByName('cbid.openclash.' + sid + '.port')[0].value = ssm[2];
			document.getElementsByName('cbid.openclash.' + sid + '.protocol')[0].value = ssm[3];
			document.getElementsByName('cbid.openclash.' + sid + '.cipher_ssr')[0].value = ssm[4];
			document.getElementsByName('cbid.openclash.' + sid + '.obfs_ssr')[0].value = ssm[5];
			document.getElementsByName('cbid.openclash.' + sid + '.password')[0].value = b64decsafe(ssm[6]);
			document.getElementsByName('cbid.openclash.' + sid + '.obfs_param')[0].value = dictvalue(pdict, 'obfsparam');
			document.getElementsByName('cbid.openclash.' + sid + '.protocol_param')[0].value = dictvalue(pdict, 'protoparam');
			var rem = pdict['remarks'];
			if (typeof (rem) != 'undefined' && rem != '' && rem.length > 0) document.getElementsByName('cbid.openclash.' + sid + '.name')[0].value = b64decutf8safe(rem);
			s.innerHTML = "<font color='green'><%:Import configuration information successfully.%></font>";
			return false;
		case "trojan":
			var url0, param = "";
			var ploc = ssu[1].indexOf("#");
			if (ploc > 0) {
				url0 = ssu[1].substr(0, ploc);
				param = ssu[1].substr(ploc + 1);
			} else {
				url0 = ssu[1]
			}
			var sstr = url0;
			document.getElementsByName('cbid.openclash.' + sid + '.type')[0].value = "trojan";
			document.getElementsByName('cbid.openclash.' + sid + '.type')[0].dispatchEvent(event);
			var team = sstr.split('@');
			var password = team[0]
			var serverPart = team[1].split(':');
			var others = serverPart[1].split('?');
			var port = parseInt(others[0]);
			var queryParam = {}
			if (others.length > 1) {
				var queryParams = others[1]
				var queryArray = queryParams.split('&');
				for (i = 0; i < queryArray.length; i++) {
					var params = queryArray[i].split('=');
					queryParam[decodeURIComponent(params[0])] = decodeURIComponent(params[1] || '');
				}
			}
			document.getElementsByName('cbid.openclash.' + sid + '.server')[0].value = serverPart[0];
			document.getElementsByName('cbid.openclash.' + sid + '.port')[0].value = port || '443';
			document.getElementsByName('cbid.openclash.' + sid + '.password')[0].value = password;
			document.getElementsByName('cbid.openclash.' + sid + '.sni')[0].value = queryParam.sni || '';
			if (queryParam.type != undefined) {
				for (i = 0; i < document.getElementById('cbi.combobox.cbid.openclash.' + sid + '.alpn.1').getElementsByTagName("option").length; i++) {
					if ( document.getElementById('cbi.combobox.cbid.openclash.' + sid + '.alpn.1').getElementsByTagName("option")[i].value == queryParam.type ) {
						document.getElementById('cbi.combobox.cbid.openclash.' + sid + '.alpn.1').getElementsByTagName("option")[i].selected=true;
					}
				}
		  }
			if (param != undefined) {
				document.getElementsByName('cbid.openclash.' + sid + '.name')[0].value = decodeURI(param);
			}
			s.innerHTML = "<font color='green'><%:Import configuration information successfully.%></font>";
			return false;
		case "vmess":
			var sstr = b64DecodeUnicode(ssu[1]);
			var ploc = sstr.indexOf("/?");
			document.getElementsByName('cbid.openclash.' + sid + '.type')[0].value = "vmess";
			document.getElementsByName('cbid.openclash.' + sid + '.type')[0].dispatchEvent(event);
			var url0, param = "";
			if (ploc > 0) {
				url0 = sstr.substr(0, ploc);
				param = sstr.substr(ploc + 2);
			}
			var ssm = JSON.parse(sstr);
			document.getElementsByName('cbid.openclash.' + sid + '.name')[0].value = ssm.ps;
			document.getElementsByName('cbid.openclash.' + sid + '.server')[0].value = ssm.add;
			document.getElementsByName('cbid.openclash.' + sid + '.port')[0].value = ssm.port;
			document.getElementsByName('cbid.openclash.' + sid + '.alterId')[0].value = ssm.aid;
			document.getElementsByName('cbid.openclash.' + sid + '.uuid')[0].value = ssm.id;
			document.getElementsByName('cbid.openclash.' + sid + '.obfs_vmess')[0].value = ssm.net;
			document.getElementsByName('cbid.openclash.' + sid + '.obfs_vmess')[0].dispatchEvent(event);
			if (ssm.net == "tcp") {
				if (ssm.type && ssm.type != "http") {
					ssm.type = "none"
					document.getElementsByName('cbid.openclash.' + sid + '.obfs_vmess')[0].value = ssm.type;
					document.getElementsByName('cbid.openclash.' + sid + '.obfs_vmess')[0].dispatchEvent(event);
				} else {
					document.getElementsByName('cbid.openclash.' + sid + '.obfs_vmess')[0].value = "http";
					document.getElementsByName('cbid.openclash.' + sid + '.obfs_vmess')[0].dispatchEvent(event);
					document.getElementsByName('cbid.openclash.' + sid + '.http_path')[0].value = ssm.path;
				}
			}
			if (ssm.net == "ws") {
				document.getElementsByName('cbid.openclash.' + sid + '.obfs_vmess')[0].value = "websocket";
				document.getElementsByName('cbid.openclash.' + sid + '.obfs_vmess')[0].dispatchEvent(event);
				document.getElementsByName('cbid.openclash.' + sid + '.custom')[0].value = ssm.host;
				document.getElementsByName('cbid.openclash.' + sid + '.path')[0].value = ssm.path;
				if (ssm.maxearlydata) {
					document.getElementsByName('cbid.openclash.' + sid + '.max_early_data')[0].value = ssm.maxearlydata;
				}
				if (ssm.earlydataheadername) {
					document.getElementsByName('cbid.openclash.' + sid + '.early_data_header_name')[0].value = ssm.earlydataheadername;
				}
			}
			if (ssm.net == "h2") {
				document.getElementsByName('cbid.openclash.' + sid + '.h2_host')[0].value = ssm.host;
				document.getElementsByName('cbid.openclash.' + sid + '.h2_path')[0].value = ssm.path;
			}
			if (ssm.tls == "tls") {
				document.getElementsByName('cbid.openclash.' + sid + '.tls')[0].value = true;
				document.getElementsByName('cbid.openclash.' + sid + '.servername')[0].value = ssm.host;
			}
			s.innerHTML = "<font color='green'><%:Import configuration information successfully.%></font>";
			return false;
		default:
			s.innerHTML = "<font color='red'><%:Invalid format.%></font>";
			return false;
		}
	}
	//]]>
</script>
<input type="button" class="btn cbi-button cbi-button-apply" value="<%:Import%>" onclick="return import_ssr_url(this, '<%=self.option%>', '<%=self.value%>')" />
<span id="<%=self.option%>-status"></span>
<%+cbi/valuefooter%>
