import { hooks, observer } from 'peepso';
import peepsodata from 'peepsodata';
import buildHashtagPattern from '../hashtags/pattern';

const hashtagsData = peepsodata.hashtags || {};

const HASHTAG_URL = hashtagsData.url;

// Build hashtag pattern based on the hashtag configuration.
const HASHTAG_PATTERN = buildHashtagPattern();

const SKIP_TAGS = [
	'a',
	'area',
	'audio',
	'base',
	'br',
	'button',
	'code',
	'col',
	'embed',
	'frame',
	'hr',
	'iframe',
	'img',
	'input',
	'keygen',
	'link',
	'meta',
	'param',
	'script',
	'select',
	'source',
	'style',
	'textarea',
	'track',
	'video',
	'wbr'
];

function filterContent(html) {
	if (html.match(HASHTAG_PATTERN)) {
		html = html.replace(HASHTAG_PATTERN, function (match, before, hashtag, label) {
			let newHtml = `${before}<a href="${HASHTAG_URL}${label}/"><span class="ps-stream-hashtag">${hashtag}</span></a>`;
			return newHtml;
		});
	}
	return html;
}

function scanElement(rootElement) {
	let elements = rootElement.querySelectorAll('*');

	// Add the root element to the element list.
	elements = [rootElement, ...elements];

	// Iterate through all elements.
	elements.forEach(element => {
		// Skip non-relevant elements.
		if (SKIP_TAGS.indexOf(element.tagName.toLowerCase()) > -1) {
			return;
		}

		let childNodes = [...element.childNodes];

		// Iterate through the element's childNodes.
		childNodes.forEach(node => {
			let text, replacer;

			// Skip non-text nodes.
			// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
			if (node.nodeType !== 3) {
				return;
			}

			// Skip empty text nodes.
			text = node.textContent;
			if (!text.trim()) {
				return;
			}

			// Skip if it does not contain mention tags.
			if (!text.match(HASHTAG_PATTERN)) {
				return;
			}

			// Generate nodes to replace the text node.
			replacer = document.createElement('div');
			replacer.innerHTML = filterContent(text);

			// Replace text node with new nodes.
			// https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
			node.replaceWith.apply(node, replacer.childNodes);

			// Update childNodes list.
			childNodes = childNodes.concat([...replacer.childNodes]);
		});
	});
}

function init() {
	// Do not run if hashtag feature is disabled.
	if (!hashtagsData.url) {
		return;
	}

	// Scan and replace every activity items added.
	observer.addFilter(
		'peepso_activity',
		$posts =>
			$posts.map(function () {
				if (this.nodeType === 1) {
					let contents = this.querySelectorAll(
						[
							'.ps-js-activity-content',
							'.ps-js-activity-extras',
							'.ps-js-activity-quote',
							'.ps-js-activity-background-text',
							'.ps-comment__content'
						].join(', ')
					);

					// Empty contents means that the whole element is the content
					// which usually comes from edit post/comment action.
					if (!contents.length) {
						contents = [this];
					}

					contents.forEach(scanElement);
				}

				return this;
			}),
		11,
		1
	);

	// Replace mention.
	hooks.addAction('post_updated', 'hashtag', function (post) {
		let postbg = post.querySelector('.ps-js-activity-background-text');
		if (postbg) {
			scanElement(postbg);
		}
	});

	// Build hashtag pattern for postbox.
	const HASHTAG_PATTERN_POSTBOX = buildHashtagPattern({ postbox: true });

	/**
	 * In-place content transform hook.
	 *
	 * @param {Element} elem
	 */
	observer.addAction(
		'postbox_content_transform',
		(elem, editor) => {
			let pattern = HASHTAG_PATTERN_POSTBOX;

			// Reset existing highlight.
			[...elem.querySelectorAll('[data-hashtag]')].forEach(span => {
				let textNode = [...span.childNodes].find(node => node.nodeType === Node.TEXT_NODE);
				let prevNode = span.previousSibling;
				let nextNode = span.nextSibling;

				if (prevNode && prevNode.nodeType === Node.TEXT_NODE) {
					prevNode.textContent += textNode.textContent;
					span.remove();
					if (nextNode && nextNode.nodeType === Node.TEXT_NODE) {
						prevNode.textContent += nextNode.textContent;
						nextNode.remove();
					}
				} else if (nextNode && nextNode.nodeType === Node.TEXT_NODE) {
					nextNode.textContent = textNode.textContent + nextNode.textContent;
					span.remove();
				} else {
					span.replaceWith.apply(span, [textNode]);
				}
			});

			(function highlight(elem) {
				[...elem.childNodes].forEach(node => {
					if (Node.TEXT_NODE === node.nodeType) {
						let text = node.textContent;

						if (text.match(pattern)) {
							let replacement = document.createElement('div');

							replacement.innerHTML = text.replace(pattern, ($0, $1, $2) => {
								let separator = $1;
								let content = $2;
								let value = content.replace(/\u200D/gi, '');

								return `${separator}<span data-highlight data-hashtag data-value="${value}">${content}</span>`;
							});

							node.replaceWith.apply(node, replacement.childNodes);
						}
					} else if (Node.ELEMENT_NODE === node.nodeType) {
						highlight(node);
					}
				});
			})(elem);
		},
		10,
		2
	);

	// Render hashtags in blogpost.
	jQuery('.peepso-wp-post-hashtags').each(function () {
		scanElement(this);
	});
}

export default { init };
