const getDate = function(){
	var d = new Date();
	return d.toLocaleDateString(lang, {day: "numeric", month: "long", year: "numeric"});
}
String.prototype.toTitleCase = function() {
	return this.replace(/\w\S*/g, function(txt) {
     return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
   });
}
String.prototype.toSentenceCase = function() {
	return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
}
String.prototype.toContent = function() {
	return this.replace(/-/g, " ");
}
String.prototype.toPath = function() {
	return this.trim().replace(/ /g, "_").replace(/-/g, "_").replace(/[\/\W]/g, "").replace(/_/g, "-");
}

const font = {
	size: 0
}

const copyFallback = (copyInfo, attr) => {
	console.log("fallback")
	var textArea = document.createElement('textarea');
	textArea.value = copyInfo;

	// Avoid scrolling to bottom
	textArea.style.top = '0';
	textArea.style.left = '0';
	textArea.style.position = 'fixed';

	document.body.appendChild(textArea);
	textArea.focus();
	textArea.select();

	try {
		var successful = document.execCommand('copy');
		setTimeout(function () {
			if (successful) {
				//copyInfo.success();
				showMessage(`Copied ${attr}.`)
			} else {
				//copyInfo.error();
				showMessage(`Copy failed (${attr}).`, false)
			}
		}, 1);
	} catch (err) {
		setTimeout(function () {
			showMessage(`Copy failed (${attr}). ${err.Message}`, false);
			
			//copyInfo.error(err);
		}, 1);
	}
	document.body.removeChild(textArea);
}

const showMessage = (m, s) => {
	s = s == undefined ? true : s;
	console.log("Copy success (navigator.clipboard)");
	let status = document.createElement("div");
	status.setAttribute("id", "copystatus");
	// status.style.display = "none";
	status.innerHTML = "<div class='"+(s ? "succeeded" : "failed")+"'>" + m + "</div>";
	document.querySelector("body").prepend(status)

	status.querySelector("div").style.top = (window.scrollY + 100)+ "px";
	setTimeout( () => {
		status.remove();
	}, 1000); 
}

const getURLVars = () => {
	var oResult = {};
	if (location.search.length > 0) {
		var aQueryString = (location.search.substr(1)).split("&");
		for (var i = 0; i < aQueryString.length; i++) {
			var aTemp = aQueryString[i].split("=");
			if (aTemp[1].length > 0) {
				oResult[aTemp[0]] = decodeURIComponent(aTemp[1].replace(/\+/g, '%20'));
			}
		}
	}
	return oResult;
}

module.exports = {
	url: (() => {
		var v = {};
		if (location.search.length > 0) {
			var qs = (location.search.substr(1)).split("&");
			for (var i = 0; i < qs.length; i++) {
				var t = qs[i].split("=");
				if (t[1].length > 0) {
					v[t[0]] = decodeURIComponent(t[1].replace(/\+/g, '%20'));
				}
			}
		}
		return v;
	})(),
	cookie: {	
		set: (name, value, expires, path, domain, secure) => {
			switch(typeof expires) {
				case "number" : 
					var d = new Date()
					expires = d.setTime(d + (expires*24*60*60*1000));
				break;
				case "object" : 
					expires = expires.toGMTString();
			}
			document.cookie= name + "=" + escape(value) +
				((expires) ? "; expires=" + expires : "") +
				("; path=/") +
				((domain) ? "; domain=" + domain : "") +
				((secure) ? "; secure" : "");
		},
		get: (cname) => {
			var name = cname + "=";
			var ca = document.cookie.split(";");
			for(var i = 0; i <ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0)===" ") {
					c = c.substring(1);
				}
				if (c.indexOf(name) === 0) {
					return c.substring(name.length,c.length);
				}
			}
			return "";
		},
		remove: (cname) => {
			module.exports.cookie.set(cname, null, new Date(null));
		},
	},
	oneClickSelect: (e, t = e.currentTarget) => {
		// In here, "this" is the element
		var range, selection;
		if (window.getSelection) {
			selection = window.getSelection();
			range = document.createRange();
			range.selectNodeContents(t);
			selection.removeAllRanges();
			selection.addRange(range);
		} else if (document.body.createTextRange) {
			range = document.body.createTextRange();
			range.moveToElementText(t);
			range.select();
		}
	},
	colour: {
		copy:  (w, t) => {
			let c = t.parentNode.getAttribute("data-" + (w=="var" ? "token" : w));
			c = w == "var" ? `var(${c})` : c;

			if (navigator.clipboard) {
				navigator.clipboard.writeText(c).then(function() {
					showMessage(`Copied ${w}.`);
				}, function(e) {
					copyFallback(c,w);
				});
			} else {
				copyFallback(c, w);
			}
		},

		positionTooltip: () => {
			document.querySelectorAll("color-pill > span").forEach((ps) =>  {
				ps.querySelectorAll("div.tooltip-tc").forEach((tip) => {
					if ( (font.size * 10) > ps.offsetLeft ) {
						tip.setAttribute("tip-position", "right");
					} else {
						tip.setAttribute("tip-position", "bottom");
					}
				});
			})
		}
	},
	getCSS: (el, prop, b = false) => {
		return window.getComputedStyle(el, null).getPropertyValue(prop);
	},
	getTabPath: (t) => {
		let url = window.location.toString();
		url = url.indexOf("?") > 0 ? url.substring(0,url.indexOf("?")) : url;
		url = `${url}?p=${t.closest("article").getAttribute("data-path")}#${t.getAttribute("id")}`
		let type = "URL";
		if (navigator.clipboard) {
			navigator.clipboard.writeText(url).then(function() {
				showMessage(`Copied ${type}.`);
			}, function(e) {
				copyFallback(url,type);
			});
		} else {
			copyFallback(url, type);
		}


	},
	init: (args = {}) => {
		const url = getURLVars();
		font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px",""));
		if (url.p !== undefined) {
			document.querySelectorAll("main article:not([data-path^='" + url.p + "'])").forEach((a) => {
				a.remove();
			});

			if (url.p == -1) {
				document.querySelector("title").innerHTML = `${url.p.toContent().toTitleCase()} | ${ document.querySelector("title").getAttribute("data-site") }`;
			} else {
				let theTitle = document.querySelectorAll("article");
				if (theTitle.length > 0) {					
					theTitle = theTitle[0].getAttribute("data-name").toContent().toTitleCase();
					if (document.querySelector("article").getAttribute("data-display") !== null) {
						theTitle = document.querySelector("article").getAttribute("data-display")
					}
					document.querySelector("title").innerHTML = `${theTitle} | ${ document.querySelector("title").getAttribute("data-site") }`
				}
			}
		}

		if (typeof args.beforeArticleLoad == "function") args.beforeArticleLoad();

		document.querySelectorAll("article").forEach((a) => {
			if ( a.getAttribute("data-template") != "none" ) {
				const observer = new IntersectionObserver(articles => {
					articles.forEach(article => {
						let a = article.target;

						if (article.isIntersecting == true) {
							let path = a.getAttribute("data-path");
							path = "patterns/" + 
							 		(a.getAttribute("data-core") == "true" ? 
							 		"core/" + path.substring(path.lastIndexOf("/") + 1) : 
							 		a.getAttribute("data-path")) 
							 		+ "/index.html";
							const ASYNC = true;
							let ajx = new XMLHttpRequest();
							ajx.onreadystatechange = () => {
								if (ajx.readyState == 4) {
									observer.unobserve(article.target);								
									switch (ajx.status) {
										case 200: 
											a.innerHTML = a.innerHTML + ajx.responseText;
											a.style.height = "auto"
											switch (a.getAttribute("data-template")) {
											 	case "pug": 
											 		a.querySelectorAll("pre").forEach((aa) => {
											 			aa.innerHTML = `<code class="${aa.getAttribute("class")}">${aa.innerHTML}</code>`;
											 		})
											 	break;
											 	case "md": 
											 		a.querySelectorAll("code").forEach((aa) => {
											 			aa.classList.add("language-html");
											 		})
											 	break;
											}

											a.querySelectorAll("code").forEach((c)=> {
												c.classList.add("line-numbers");
												c.innerHTML = c.innerHTML.replace(/</g, "&lt;");
												c.classList.add("copy-to-clipboard-button");
											})
											if (typeof args.success == "function") args.success(a);

											Prism.highlightAll();

											a.querySelectorAll("code").forEach((c)=> {
												c.onclick = (e) => {
													module.exports.oneClickSelect(e);
												}
											})


											module.exports.colour.positionTooltip();
											window.onresize = () => {
												module.exports.colour.positionTooltip();
											}

											a.querySelectorAll("name > span, color-pill > span").forEach((pill) => {
												pill.onclick = (e) => {
													e.preventDefault();
													let w = "";
													if (e.metaKey || e.ctrlKey || e.keyCode == 91 || e.keyCode == 224) {
														w = "var";
													} else if (e.altKey) {
														w = "token"
													} else if (e.shiftKey) {
														w = "rgb";
													} else {
														w = "hex";
													}
													module.exports.colour.copy(w, pill);
												}
											})
										break;

										case 404: 
											if (typeof args.notFound == "function") args.notFound(a, path);
										break;

										default:
											console.log("uncaught http error", { status: ajx.status, path: a.getAttribute("data-path") });
									}

									a.style.height = "auto";
									
									if (typeof args.done == "function") args.done(a);

								}
							};
							ajx.open("GET", path, ASYNC);
							ajx.send();

						}
					})
				}, { threshold: 0, rootMargin: "100%" })

				observer.observe(a);

			} else {
				a.style.height = "auto";
			}
		})

		if (typeof args.afterArticleLoad == "function") args.afterArticleLoad();
	}
};