'use strict';

var plugins = module.parent.require('./plugins'),
	fs = require('fs'),
	path = require('path'),
	util = require('util'),
	app;

var plugin = {};

plugin.parse = function(data, callback) {

	if (data && typeof data === 'string') {
		// preview
		data = parser(data);
	} else if (data.postData && data.postData.content) {
		// post
		data.postData.content = parser(data.postData.content);
	} else if (data.userData && data.userData.signature) {
		// signature
		data.userData.signature = parser(data.userData.signature);
	}

	callback(null, data);
}

// replace [spoiler] fake tags with real tags
function parser(data) {
	
	// replace escaped text with a guid temporarily
	var pre = /(?:<pre(.|\n)*?<\/pre>|<code(.|\n)*?<\/code>)/g;
	var preBlocks = [];
	var preTag = '88888888-8888-4888-2888-888888888888'.replace(/[82]/g, (c) => (Math.random() * c * 2 ^ 8).toString(16));
	data = data.replace(pre, function(match) {
		preBlocks.push(match);
		return preTag;
	});

	// replace image and multi-line spoilers
	data = data.replace(/\[spoiler\](.*?(\n|<img).*?)\[\/spoiler\]/g, function(_, match) {
		return '<div class="blur" onclick="toggleBlur(this);">' + match + '</div>';
	});
	// replace inline spoilers
	data = data.replace(/\[spoiler\](.*?)\[\/spoiler\]/g, function(_, match) {
		return '<span class="blur" onclick="toggleBlur(this);">' + match + '</span>';
	});

	// replace guid with original escaped text
	var preTagRegex = new RegExp(preTag, 'g');
	data = data.replace(preTagRegex, function() {
		return preBlocks.shift();
	});

	return data;
}

module.exports = plugin;

@@ -1032,23 +1032,8 @@
 age 
-and multi-line 
 spoi
@@ -1076,21 +1076,26 @@
 r%5C%5D(
-.*?(%5Cn%7C%3Cimg).
+(.%7C%5Cn)*?%3Cimg(.%7C%5Cn)
 *?)%5C
@@ -1401,32 +1401,232 @@
 %3C/span%3E';%0D%0A%09%7D);%0D
+%0A%09// replace multi-line spoilers%0D%0A%09data = data.replace(/%5C%5Bspoiler%5C%5D((.%7C%5Cn)*?)%5C%5B%5C/spoiler%5C%5D/g, function(_, match) %7B%0D%0A%09%09return '%3Cdiv class=%22blur%22 onclick=%22toggleBlur(this);%22%3E' + match + '%3C/div%3E';%0D%0A%09%7D);%0D
 %0A%0D%0A%09// replace g

Fix multi-line spoilers