// ==UserScript==
// @name        2chen_mod_log
// @description fun with colours
// @version     2
// @match       https://*.2chen.org/html/mod-log/*
// @match       https://*.2chen.org/html/reports/*
// @match       https://*.2chen.moe/html/mod-log/*
// @match       https://*.2chen.moe/html/reports/*
// @grant       GM.xmlHttpRequest
// ==/UserScript==

(function () {
	'use strict';
	var file_types = ['jpg', 'png', 'gif', 'webm', 'pdf', 'svg', 'mp4', 'mp3', 'ogg', 'zip', '7z', 'tar.gz', 'tar.xz', 'flac', 'no_file', 'txt', 'webp', 'rar', 'cbz', 'cbr', 'mp4 [hevc]'],
	prev_fields,
//	time_relative = false,
	time_relative = true,
	date_now = Date.now(),
	post_links = true,
	post_data = {},
	reports = new Set(),
	reports_page = document.location.href.includes('/reports/'),
	table = document.querySelector('table');
	document.body.style.background = '#222222';
	table.style.background = '#202020';
	table.style.border = '1px solid #cccccc';
	table.style.margin = 'auto';
	Array.from(table.querySelectorAll('tr')).reverse().forEach(function (row) {
		if (row.querySelector('th')) {
			row.style.color = '#cccccc';
			return;
		}
		var [cells, type,by,post,time,data,duration] = (function () {
			var r = [],
			cells = row.querySelectorAll('td');
			r.push(cells);
			cells.forEach(function (cell) {
//				cell.style.border = '1px solid #cccccc';
				r.push(cell.innerText);
			});
			return r;
		})(),
		age = secondsToTime(Math.floor((date_now - (new Date(time))) / 1000)),
		fields = [type,by,time,data,duration].join('|');
		if (prev_fields === fields || (reports_page && reports.has(by))) {
			row.style.color = 'grey';
		} else if (by === 'system' || reports_page) {
			row.style.color = 'white';
		} else if (by === 'admin') {
			row.style.color = 'red';
		} else {
			row.style.color = 'lime';
		}
		prev_fields = fields;
		if (reports_page) reports.add(by); // post id
		cells[3].title = time_relative ? time : age;
		if (time_relative) cells[3].innerText = age;
		if (post_links) {
			var post_cell = cells[reports_page ? 1 : 2],
			next_cell = post_cell.nextSibling,
			post_link = post_cell.querySelector('a[data-id]'),
			post_id = post_link.getAttribute('data-id'),
			post_div = document.createElement('div'),
			post_generated = false;
			post_div.style.background = 'red';
			post_div.style.position = 'absolute';
			post_div.style.display = 'none';
			post_div.append(document.createTextNode(post_id));
			post_cell.append(post_div);
			post_link.addEventListener('mouseover', function () {
				var rect = next_cell.getBoundingClientRect();
//				post_div.style.width = rect.width + 'px';
				post_div.style.left = (window.scrollX + rect.left) + 'px';
				post_div.style.top = (window.scrollY + rect.top) + 'px';
				post_div.style.display = 'block';
				if (post_generated) return;
				load_post(post_id, function (data) {
					generate_post(post_div, JSON.parse(data));
					post_generated = true;
				});
			});
			post_link.addEventListener('mouseout', function () {
				post_div.style.display = 'none';
			});
		}
	});
	function text_div(v, styles) {
		var el = document.createElement('div');
		if (styles) {
			for (var [property, value] of Object.entries(styles)) {
				el.style[property] = value;
			}
		}
		el.append(document.createTextNode(v));
		return el;
	}
	function file_type(v) {
		return file_types.hasOwnProperty(v) ? file_types[v] : '?';
	}
	function generate_post(link, data) {
		var post = document.createElement('article'),
		header = document.createElement('header'),
		post_container = document.createElement('div'),
		post_block = document.createElement('blockquote'),
		time = new Date(data.time*1000),
		age = secondsToTime(Math.floor((date_now - time) / 1000));
		post.style.display = 'flex';
		post.style.flexDirection = 'column';
		post.style.alignItems = 'flex-start';
		post.style.background = '#2f343e';
		post.style.color = '#c5c8c6';
		header.style.display = 'block';
		header.style.padding = '10px';
		post_block.style.minWidth = '25em';
		header.append(text_div('No.' + data.id));
		header.append(text_div(time.toISOString()));
		header.append(text_div(age));
		if (data.image !== null) {
			var image_container = document.createElement('figure'),
			image = document.createElement('img');
			image_container.style.float = 'left';
			image_container.style.margin = '5px 10px 0 0';
			image_container.style.padding = '10px';
			image.src = '/assets/images/thumb/' + data.image.sha1 + '.jpg';
			image_container.append(image);
			post_container.append(image_container);
			header.append(document.createElement('br'));
			header.append(text_div(data.image.name + '.' + file_type(data.image.file_type), {color: 'teal'}));
			['artist', 'title'].filter(p => data.image[p] !== '').forEach(p => header.append(text_div(p + ': ' + data.image[p])));
		}
		if (data.moderation !== null) {
			header.append(document.createElement('br'));
			data.moderation.forEach(function (action) {
				var action_text;
				switch (action.type) {
					case 0: { // https://2chen.moe/tv/5#p834
						action_text = 'BANNED BY "' + action.by + '" FOR ' + secondsToTime(action.length, false) + ' FOR "' + action.data + '"';
						break;
					}
					case 1: { // https://2chen.moe/tv/4025#p5618
						action_text = 'UNBANNED BY "' + action.by + '"';
						break;
					}
					case 2: { // https://2chen.moe/tv/5#p1889
						action_text = 'DELETED BY "' + action.by + '"';
						break;
					}
					case 3: { // https://2chen.moe/tv/5#p1889
						action_text = 'IMAGE DELETED BY "' + action.by + '"';
						break;
					}
					case 4: { // https://2chen.moe/tv/2024#p3090
						action_text = 'IMAGE SPOILERED BY "' + action.by + '"';
						break;
					}
					case 5: { // https://2chen.moe/tv/1#p1
						action_text = 'THREAD LOCKED BY "' + action.by + '"';
						break;
					}
//					case 6: { // ??
//						action_text = '?? BY "' + action.by + '"';
//						break;
//					}
					case 7: { // https://2chen.moe/tv/5#p1847
						action_text = 'POSTS OF THE SAME IP WERE VIEWED BY "' + action.by + '"';
						break;
					}
					case 8: { // https://2chen.moe/tv/5014#p5014
						action_text = 'POST PURGED BY "' + action.by + '" FOR "' + action.data + '"';
						break;
					}
					case 9: { // https://2chen.moe/tv/4025#p4679
						action_text = 'SHADOW BINNED BY "' + action.by + '" FOR ' + secondsToTime(action.length, false) + ' FOR "' + action.data + '"';
						break;
					}
					case 10: { // https://2chen.moe/tv/1375636#p1898706
						action_text = 'POSTING BANNED BY "' + action.by + '" FOR ' + secondsToTime(action.length, false) + ' FOR "' + action.data + '"';
						break;
					}
					default: {
						action_text = JSON.stringify(action);
					}
				}
				header.append(text_div(action_text, {
					color: 'red',
					fontWeight: 'bold'
				}));
			});
		}
		post_block.innerText = data.body;
		post_container.append(post_block);
		post.append(header);
		post.append(post_container);
		link.style.background = '';
		link.innerHTML = post.outerHTML;
	}
	function load_post(post_id, callback) {
		if (post_data.hasOwnProperty(post_id)) {
			callback(post_data[post_id]);
		} else {
			GM.xmlHttpRequest({
				method: 'GET',
				url: 'https://2chen.moe/json/post/' + post_id,
				onload: function (response) {
					if (response.status === 200) {
						callback(post_data[post_id] = response.responseText);
					} else {
						console.error(response);
					}
				}
			});
		}
	}
	function secondsToTime(s, relative=true) {
		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(', ') + (relative ? ' ago' : '');
	}
})();