/* first things first, we need to scan over the document and see
 * if there are any UI elements unfortunate enough to need
 * interactivity beyond what native HTML+CSS can provide. if so,
 * we attach the appropriate listeners to them. */
window.addEventListener('load', function() {
	/* social media is less fun when you can't just click on a tweet
	 * to insta-like or -retweet it. this is unfortunately not possible
	 * (except in various hideously shitty ways) without javascript. */
	let mk      =  elt => document.createElement(elt);
	let posturl = post => post.querySelector('.permalink').attributes.getNamedItem('href').value;
	let focused =   () => document.querySelector('textarea:focus, input:focus, button:focus, select:focus, a[href]:focus') != null;
	function postReq(url,act,elt) {
		fetch(new Request(url, {
			method: 'POST',
			body: 'act='+act
		})).then(function(resp) {
			if (resp.ok && resp.status == 200) {
				let i = parseInt(elt.innerHTML)
				if (isNaN(i)) {i=0}
				elt.innerHTML = (i+1).toString()
				elt.animate({
					transform: ['scale(1.4)', 'scale(1.0)'],
					filter: ['brightness(1)','brightness(0)']
				},200)
			}
		})
	}

	function onkey(elt, fn) {
		elt.addEventListener('keydown', function(ev) {
			if (!window._liveTweetMap) { return; }
			if (event.isComposing || event.keyCode === 229) { return; } // 🙄
			return fn(ev);
		})
	}

	/* div-based like and rt aren't very keyboard-friendly. add a replacement */
	if (document.querySelector('body.timeline, body.profile, body.post') != null) {
		onkey(window, function(event) {
			if (focused()) {return;}
			let cururl = window._liveTweetMap.cur;
			let nexturl = null;
			if (event.key == 'j') { // down
				if (cururl == null) {
					nexturl = window._liveTweetMap.first
				} else {
					nexturl = window._liveTweetMap.map.get(cururl).next
				}
			} else if (event.key == 'k') { // up
				if (cururl == null) {
					nexturl = window._liveTweetMap.last
				} else {
					nexturl = window._liveTweetMap.map.get(cururl).prev
				}
			} else if (cururl != null) {
				let post = window._liveTweetMap.map.get(cururl).me
				if (event.key == 'f') { // fave
					postReq(cururl, 'like', post.querySelector('.stats>.like'))
				} else if (event.key == 'r') { // rt
					postReq(cururl, 'rt', post.querySelector('.stats>.rt'))
				} else if (event.key == 'd') { // rt
					if (post.attributes.getNamedItem('data-own')) {
						window.location = cururl + '/del';
					}
				} else if (event.key == 'Enter') { // nav
					window.location = cururl;
					return;
				}
			}
			if (nexturl != null) {
				if (cururl != null) {
					let cur = window._liveTweetMap.map.get(cururl);
					cur.me.classList.remove('live-selected')
				}
				let next = window._liveTweetMap.map.get(nexturl);
				next.me.classList.add('live-selected')
				window._liveTweetMap.cur = nexturl
			}
		});
	}
	
	/* make ctrl-enter submit poasts. why the fuck does this require jabbascript */
	document.querySelectorAll('form').forEach(form => form.querySelectorAll('textarea').forEach(function(te) {
		let submitbtn = form.querySelector('button[name], input[type="submit"][name], input[type="image"][name]');
		onkey(te, function(e) {
			if(e.ctrlKey && e.keyCode == 13) {
				if(submitbtn == null) { form.submit(); } else { submitbtn.click(); }
				// are you kidding me with this shit
				return true;
			}
		})
	}));

	/* allow response to queries via the keyboard */
	let queryform = document.querySelector('body.query form');
	if(queryform != null) {
		okbtn = queryform.querySelector('button[name]');
		nobtn = queryform.querySelector('.button.no, button.no');
		onkey(window, function(e) {
			if (focused()) {return;}
			if (e.keyCode == 13 || e.key == 'y') {
				if (okbtn != null) { okbtn.click() } else { queryform.submit() }
			} else if (e.key == 'Escape' || e.key == 'n') {
				if (nobtn != null) { nobtn.click() } else { window.history.back() }
			}
		});
	}

	function attachButtons() {
		let last = null;
		let newmap = { cur: null, first: null, last: null, map: new Map() }
		document.querySelectorAll('main article.post').forEach(function(post){
			let url = posturl(post);
			if (last == null) { newmap.first = url; } else {
				newmap.map.get(last).next = url
			}
			newmap.map.set(url, {me: post, prev: last, next: null})
			last = url
			if (window._liveTweetMap && window._liveTweetMap.cur == url) {
				post.classList.add('live-selected');
			}

			let stats = post.querySelector('.stats');
			if (stats == null) {
				/* no stats box; create one */
				let n = mk('div');
				n.classList.add('stats');
				post.appendChild(n);
				stats = n
			}
			function ensureElt(cls, before) {
				let s = stats.querySelector('.' + cls);
				if (s == null) {
					let n = mk('div');
					n.classList.add(cls);
					if (before == null) { stats.appendChild(n) } else {
						stats.insertBefore(n,stats.querySelector(before))
					}
					return n
				} else { return s }
			}
			let like = ensureElt('like', null);
			let rt   = ensureElt('rt','.like');
			function activate(elt,name) {
				elt.addEventListener('click', function(e) { postReq(url,name,elt) });
				elt.style.setProperty('cursor','pointer');
				elt.setAttribute('tabindex','0');
			}
			activate(like,'like');
			activate(rt,'rt');
		});
		newmap.last = last
		if (window._liveTweetMap) {
			newmap.cur = window._liveTweetMap.cur // TODO handle vanishments
		}
		window._liveTweetMap = newmap;
	}

	/* update hue-picker background when slider is adjusted */
	document.querySelectorAll('.color-picker').forEach(function(box) {
		let slider = box.querySelector('[data-color-pick]');
		box.style.setProperty('--hue', slider.value);
		slider.addEventListener('input', function(e) {
			box.style.setProperty('--hue', e.target.value);
		});
	});

	/* the main purpose of this script -- by marking itself with the
	 * data-live property, an html element registers itself for live
	 * updates from the server. this is pretty straightforward: we
	 * retrieve this url from the server as a get request, create a
	 * tree from its html, find the element in question, ferret out
	 * any deltas, and apply them. */
	document.querySelectorAll('*[data-live]').forEach(function(container) {
		let interv = parseFloat(container.attributes.getNamedItem('data-live').nodeValue) * 1000;
		container._liveLastArrival = 0; /* TODO include initial value in document */

		window.setInterval(function() {
			let req = new Request(window.location, {
				method: 'GET',
				headers: { 'X-Live-Last-Arrival': container._liveLastArrival }
			})
			
			fetch(req).then(function(resp) {
				if (!resp.ok) return;
				let newest = parseInt(resp.headers.get('X-Live-Newest-Artifact'));
				if (newest == container._liveLastArrival) { // != also handles some deletions
					resp.body.cancel();
					return;
				}
				container._liveLastArrival = newest

				resp.text().then(function(htmlbody) {
					let parser = new DOMParser();
					let newdoc = parser.parseFromString(htmlbody,'text/html')
					container.innerHTML = newdoc.getElementById(container.id).innerHTML;
					attachButtons();
				})
			})
		}, interv)
	});

	attachButtons();
});
