const fs = require('fs');
const f = fs.readFileSync('quotes.txt', 'utf8');
const { marked, lexer } = require('marked');
const { inspect } = require('util');

function resolveLexerData(data) {
	switch (data.type) {
		case 'em':
			return [{
				text: data.tokens.map(t => resolveLexerData(t)),
				italic: true
			}];
		case 'strong':
			return [{
				text: data.tokens.map(t => resolveLexerData(t)),
				bold: true
			}]
		case 'del':
			return [{
				text: data.tokens.map(t => resolveLexerData(t)),
				strikethrough: true
			}]
		case 'text':
			return {text: data.raw};
		default:
			if (data.tokens) {
				return data.tokens.map(t => resolveLexerData(t));
			}
			throw new Error('don\'t know what to do: ' + JSON.stringify(data));
	}
}

function flattenData(data, italic, bold, strikethrough) {
	//console.log(data);
	if (data.length) return data.flatMap(l => flattenData(l, italic, bold, strikethrough));
	if (typeof data.text === 'string') {
		return {
			text: data.text,
			italic: italic,
			bold: bold,
			strikethrough: strikethrough
		};
	}

	return flattenData(data.text, italic || data.italic, bold || data.bold, strikethrough || data.strikethrough);
}

function toMCString(text) {
	const parsed = lexer(text);
	const resolved = resolveLexerData(parsed[0]);
	const flattened = resolved.map(l => flattenData(l));
	return flattened;
}

f
	.split('%')
	.map(s => s.trim())
	.map(q => ({
		"title": {
			"text": "Random #evidence quote",
			"underlined": true,
			"color": "gold"
		},
		"tip": toMCString(q)
	}))
	.map(json => JSON.stringify(json))
	.forEach((content, i) => {
		fs.writeFileSync(`quote-${i}.json`, content);
	});
