import peepsodata from 'peepsodata';

const hashtagsData = peepsodata.hashtags || {};

const HASHTAG_EVERYTHING = +hashtagsData.everything || 0;
const HASHTAG_MIN_LENGTH = HASHTAG_EVERYTHING ? 0 : +hashtagsData.min_length || 0;
const HASHTAG_MAX_LENGTH = HASHTAG_EVERYTHING ? 10000 : +hashtagsData.max_length || 10000;
const HASHTAG_MUST_START_WITH_LETTER = HASHTAG_EVERYTHING
	? 0
	: +hashtagsData.must_start_with_letter || 0;

/**
 * Build the strict hashtag pattern: a hashtag only counts at the very beginning
 * of the text, at the beginning of a new line, or when surrounded by whitespace.
 * No other delimiters - punctuation, markup or URLs glued to a hashtag disqualify it.
 *
 * @param {Object} [options]
 * @param {boolean} [options.postbox] Build the postbox variant, which tolerates
 *   the zero-width-joiner caret markers inserted by the editor.
 * @returns {RegExp}
 */
export default function buildHashtagPattern(options) {
	let postbox = !!(options && options.postbox);
	let minLength = Math.max(0, HASHTAG_MIN_LENGTH - (HASHTAG_MUST_START_WITH_LETTER ? 1 : 0));
	let maxLength = Math.max(0, HASHTAG_MAX_LENGTH - (HASHTAG_MUST_START_WITH_LETTER ? 1 : 0));
	let pattern;

	if (postbox) {
		let caret = '(?:\\u200D\\u200D)';
		// Safari still doesn't support lookbehind pattern, unfortunately.
		// https://caniuse.com/js-regexp-lookbehind
		let startSeparator = `((?:^|\\s|&nbsp;)${caret}?)`;

		if (HASHTAG_EVERYTHING) {
			pattern = `${startSeparator}(#${caret}?(?:[^#\\s\\u200D]${caret}?)+)(?=\\s|$)`;
		} else {
			pattern = `${startSeparator}(#${caret}?(?:${
				HASHTAG_MUST_START_WITH_LETTER ? `[a-z]${caret}?` : ''
			}(?:[a-z0-9]${caret}?){${minLength},${maxLength}}))(?=\\s|$)`;
		}
	} else if (HASHTAG_EVERYTHING) {
		pattern = '(^|\\s)(#([^#\\s<]+))(?=\\s|$)';
	} else {
		pattern =
			'(^|\\s)(#(' +
			(HASHTAG_MUST_START_WITH_LETTER ? '[a-z]' : '') +
			'[a-z0-9]{' +
			minLength +
			',' +
			maxLength +
			'}' +
			'))(?=\\s|$)';
	}

	return new RegExp(pattern, 'ig');
}
