"use babel";

const shell = require("shell");

// from http://stackoverflow.com/a/6969486/806777
function escapeRegExp(str) {
	return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function isHyperlink(link) {
	return /^https?:\/\/.+/.test(link);
}

function getHyperlink(textEditor, range) {
	const token = textEditor.tokenForBufferPosition(range.start);

	if (token && token.value) {
		const linkText = token.value.trim();
		if (isHyperlink(linkText)) {
			return {
				link: linkText,
				linkText,
			};
		} else if (textEditor.getGrammar().scopeName === "source.gfm") {
			let link = null;
			mdLinkRegex = new RegExp("^\\s*\\[" + escapeRegExp(linkText) + "\\]\\s*:\\s*(\\S+)\\s*$", "ig");
			textEditor.getBuffer().backwardsScan(mdLinkRegex, (found) => {
				const matchedLink = found.match[1];
				if (isHyperlink(matchedLink)) {
					link = matchedLink;
					found.stop();
				}
			});
			if (link) {
				return {
					link,
					linkText,
				};
			}
		}
	}
}

function getRange(textEditor, range, linkText) {
	const searchStart = [range.start.row, range.start.column - linkText.length];
	const searchEnd = [range.end.row, range.end.column + linkText.length];
	const searchRange = [searchStart, searchEnd];

	const linkRegexp = new RegExp(escapeRegExp(linkText));
	let linkRange = null;

	textEditor.scanInBufferRange(linkRegexp, searchRange, (found) => {
		linkRange = found.range;
		found.stop();
	});
	return linkRange;
}

module.exports = {
	getProvider() {
		return {
			providerName: "hyperlink-hyperclick",
			getSuggestionForWord(textEditor, text, range) {

				const {
					link,
					linkText
				} = getHyperlink(textEditor, range);
				if (link) {
					const linkRange = getRange(textEditor, range, linkText);
					return {
						range: linkRange,
						callback() {
							shell.openExternal(link);
						},
					};
				}
			},
		};
	},
};

@@ -224,31 +224,267 @@
  %7B%0A%09
-return /%5Ehttps?:%5C/%5C/.+/
+const protocols = atom.config.get(%22hyperlink-hyperclick.protocols%22);%0A%09const protocolsEscaped = protocols.map((val) =%3E %7B%0A%09%09return escapeRegExp(val);%0A%09%7D);%0A%09const protocolRegexp = new RegExp(%22%5E(%22 + protocolsEscaped.join(%22%7C%22) + %22)://%5C%5CS+%22);%0A%09return protocolRegexp
 .tes
@@ -854,16 +854,17 @@
 inkRegex
+p
  = new R
@@ -992,16 +992,17 @@
 inkRegex
+p
 , (found
@@ -1701,16 +1701,225 @@
 rts = %7B%0A
+%09config: %7B%0A%09%09protocols: %7B%0A%09%09%09description: %22Comma separated list of protocols to open when ctrl+clicked%22,%0A%09%09%09type: %22array%22,%0A%09%09%09default: %5B%22http%22, %22https%22, %22mailto%22%5D,%0A%09%09%09items: %7B%0A%09%09%09%09type: %22string%22%0A%09%09%09%7D,%0A%09%09%7D%0A%09%7D,%0A
 %09getProv
@@ -1979,16 +1979,16 @@
 click%22,%0A
+
 %09%09%09getSu
@@ -2030,17 +2030,16 @@
 ange) %7B%0A
-%0A
 %09%09%09%09cons

add config option for protocols