// ==UserScript==
// @name        2chen
// @description
// @version     1
// @match       https://*.2chen.org/*
// @match       https://*.2chen.moe/*
// @grant       GM_setClipboard
// ==/UserScript==

(function () {
	'use strict';
	var banner = document.querySelector('span#banner');
	function add_checkbox(name, value) {
		var input = document.createElement('input');
		var label = document.createElement('label');
		input.type = 'checkbox';
		input.checked = localStorage.getItem(value) === 'true';
		label.innerText = name;
		label.append(input);
		banner.append(label);
		return input;
	}
	var button_rename = add_checkbox('Rename', 'randomFileNames');
	button_rename.onclick = function () {
		document.querySelector('input#randomFileNames').click();
		this.checked = localStorage.getItem('randomFileNames') === 'true';
	};
	var button_autopost = add_checkbox('Auto-post', 'autoPost');
	button_autopost.onclick = function () {
		localStorage.setItem('autoPost', this.checked);
	};
	function add_link(name, bind) {
		var link = document.createElement('a');
		link.append(document.createTextNode(name));
		link.onclick = bind;
		return link;
	}
	var menu_action,
	menu_try = function (post) {
		var menu = post.querySelector('ul.popup-menu');
		if (menu !== null) {
			menu_select(menu);
		} else {
			menu_observer.observe(post, {attributes: true, childList: true, subtree: true});
			post.querySelector('a.control').click();
		}
	},
	menu_select = function (menu) {
		menu.querySelector('li[data-id="' + menu_action + '"]').click();
	},
	menu_observer = new MutationObserver(function (mutations) {
		mutations.forEach(function (mutation) {
			if ((mutation.type === 'childList')
			&& (mutation.target.tagName === 'A')
			&& (mutation.target.classList.contains('control'))) {
				menu_select(mutation.target.querySelector('ul.popup-menu'));
				menu_observer.disconnect();
			}
		});
	}),
	hide = function (post) {
		menu_action = 'hide';
		menu_try(post);
	},
	report = function (post) {
		close_report_forms();
		menu_action = 'report';
		menu_try(post);
	},
	viewFileNames = function (post) {
		if (close_post_collections() === 0 || viewedFileNames !== post.id) {
			menu_action = 'viewFileNames';
			menu_try(post);
		}
		viewedFileNames = post.id;
	},
	viewedFileNames,
	button_hide = function () {
		hide(this.parentNode.parentNode);
	},
	button_report = function () {
		report(this.parentNode.parentNode);
	},
	button_viewFileNames = function () {
		viewFileNames(this.parentNode.parentNode);
	},
	button_posts = function () {
		document.querySelectorAll('article:not(.buttoned):not(.reply-form)').forEach(function (post) {
			post.classList.add('buttoned');
			post.querySelector('a.control').style.display = 'none';
			if (!post.parentNode.classList.contains('post-collection')) {
				var info_line = post.querySelector('header.spaced');
				info_line.prepend(add_link('[-]', button_hide));
				info_line.append(add_link('[!]', button_report));
			}
		});
	},
	sauce_posts = function () {
		document.querySelectorAll('article.media:not(.sauced)').forEach(function (post) {
			post.classList.add('sauced');
			var aweme_id,
			info_line = post.querySelector('figcaption'),
			file_link = info_line.querySelector('a[download]'),
			file_info = info_line.querySelectorAll('span.fileinfo span'),
			link_name = file_link.innerText,
			file_name = file_info[file_info.length - 1].innerText;
			if (aweme_id = match_aweme_id(link_name, file_name)) {
				var link = document.createElement('a');
				link.href = 'https://www.tiktok.com/share/video/' + aweme_id;
				link.target = '_blank';
				link.style.color = 'lime';
				link.append(document.createTextNode('sauce'));
				info_line.append(link);
//				file_link.title = new Date(aweme_id/2**32*1000).toLocaleString();
				var aweme_time = new Date(aweme_id/2**32*1000);
				file_link.addEventListener('mouseover', function () {
					this.title = aweme_time.toLocaleString() + '\n' + secondsToTime(Math.floor((new Date(Date.now() - aweme_time) / 1000)));
				});
			}
//			file_link.href = post.querySelector('div.post-container > figure > a').href
			if (!post.parentNode.classList.contains('post-collection')) {
				info_line.append(add_link('[?]', button_viewFileNames));
			}
		});
	},
	banner_observer = new MutationObserver(function (mutations) {
		try {
			document.querySelector('a#banner-watcher').click();
			banner_observer.disconnect();
		} catch {}
	}),
	last_logged,
	thread = document.querySelector('section#thread-container');
	banner_observer.observe(banner, {attributes: true, childList: true, subtree: true});
	button_posts();
	sauce_posts();
	new MutationObserver(function () {
		button_posts();
		sauce_posts();
		if (localStorage.getItem('autoPost') === 'true') {
			try {
				document.querySelector('article.media.reply-form div#post-controls input[value=Done]').click();
			} catch {}
		}
		document.querySelectorAll('div#megu-tv video:not(.hidden):not(.logged)').forEach(function (video) {
			if (last_logged !== video.src) {
				last_logged = video.src;
				var file = video.src,
				file_name = file.replace(/^.+\//, ''),
				file_hash = file_name.replace(/\.[^.]+$/, ''),
				item = document.createElement('div'),
				item_html = `
					<figure style="margin: 0px;">
					<a href="/assets/images/src/${file_name}" target="_blank">
					<img src="/assets/images/thumb/${file_hash}.jpg">
					</a>
					</figure>
				`,
				target_node = thread,
				last_child = thread.lastChild;
				if (last_child.id === 'megu-tv-log') {
					target_node = last_child;
				} else {
					item_html = `
						<article id ="megu-tv-log" class="glass media buttoned sauced" style="background-color: teal; display: inline-flex; flex-direction: row; flex-wrap: wrap; align-content: flex-start;">
						${item_html}
						</article>
					`;
				}
				target_node.appendChild(item);
				item.outerHTML = item_html.trim();
			}
			video.classList.add('logged');
		});
		document.querySelectorAll('article.megu-tv-log img:not(.timed)').forEach(function (video) {
			var time = new Date();
			video.addEventListener('mouseover', function () {
				this.title = time.toLocaleString() + '\n' + secondsToTime(Math.floor((new Date(Date.now() - time) / 1000)));
			});
			video.classList.add('timed');
		});
	}).observe(document, {attributes: true, childList: true, subtree: true});
	function match_aweme_id() {
		for (var match, i = 0; i < arguments.length; i++) {
			if (match = arguments[i].match(/(?:\b|\D)([67]\d{18})(?:\b|\D)/)) {
				return match[1];
			}
		}
	}
	function secondsToTime(s) {
		if (s === 0) {
			return 'just now';
		}
		const units = ['second', 'minute', 'hour', 'day', 'month', 'year'];
		const divide = [60, 60, 24, 30, 12];
		let interval = [1];
		for (let i = 0; i < divide.length; i++) {
			interval.push(interval[i] * divide[i]);
		}
		interval[5] = interval[3] * 365; // year = day * 365
		let time = s;
		let format = [];
		for (let i = interval.length; i >= 0; i--) {
			if (time >= interval[i]) {
				let unit = Math.floor(time / interval[i]);
				format.push(unit + ' ' + units[i] + (unit === 1 ? '' : 's'));
				time -= unit * interval[i];
			}
		}
		format.splice(2);
		return format.join(', ') + ' ago';
	}
	document.addEventListener('keydown', function (e) {
		if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return;
		if (document.activeElement.tagName === 'BODY') {
			switch (e.key) {
				case 'i': {
					e.preventDefault();
					var links = Array.from(document.querySelectorAll('a[href*="tiktok.com"]')).map(link => link.href);
					if (links.length && confirm(links.length)) {
						GM_setClipboard(links.join('\n'));
					}
					break;
				}
				case 'Escape': {
					e.preventDefault();
					close_post_collections();
					close_report_forms();
					break;
				}
				case 'r': {
					e.preventDefault();
					button_rename.click();
					break;
				}
				case 'a': {
					e.preventDefault();
					button_autopost.click();
					break;
				}
				case 'k': {
					e.preventDefault();
					document.querySelector('a#banner-watcher').click();
					break;
				}
				case 'o': {
					e.preventDefault();
					document.querySelector('a#banner-options').click();
					break;
				}
				case 'm': {
					e.preventDefault();
					document.querySelector('div#megu-tv').click();
					break;
				}
				case 'l': {
					e.preventDefault();
					document.querySelectorAll('article.deleted').forEach(function (post) {
						post.remove();
					});
					break;
				}
				case '1': {
					e.preventDefault();
					document.querySelectorAll('article').forEach(function (post) {
						if (!post.querySelector('b.name i')) post.remove();
					});
					break;
				}
				case '2': {
					e.preventDefault();
					document.querySelectorAll('article').forEach(function (post) {
						var i = false;
						post.querySelectorAll('div.post-container a.post-link').forEach(function (link) {
							i = i || link.innerText.substr(-5) === '(You)';
						});
						if (i === false) post.remove();
					});
					break;
				}
				case 'Delete':
				case 'Insert':
				case 'x':
				case 'j':
				case 'f': {
					e.preventDefault();
					var post = document.querySelector('article:hover');
					if (post) {
						switch (e.key) {
							case 'Delete':
							case 'x': {
								hide(post);
								break;
							}
							case 'Insert':
							case 'j': {
								report(post);
								break;
							}
							case 'f': {
								viewFileNames(post);
								break;
							}
							default: return;
						}
					}
					break;
				}
				default: return;
			}
		}
	});
	function close_post_collections() {
		var closed = 0;
		document.querySelectorAll('div.post-collection > a:first-child').forEach(function (close_button) {
			close_button.click();
			closed += 1;
		});
		return closed;
	}
	function close_report_forms() {
		var closed = 0;
		document.querySelectorAll('form.report-form').forEach(function (report_form) {
			report_form.querySelector('input[name="cancel"]').click();
			closed += 1;
		});
		return closed;
	}
})();