'use strict';

const url = require('url');

module.exports = function(config, ircbot, utils) {
	ircbot.addListener('message', function(from, to, message) {
		const parts = message.split(' ');

		for (let i = 0; i < parts.length; i++) {
			try {
				const urlObj = url.parse(parts[i]);
				utils.request.get(urlObj.href, function(data) {
					const matches = data.match(/<title ?.*?>([^<]*)<\/title>/i);
					
					if (matches && matches[1]) {
						// we have found a title element
						ircbot.say(to, '^ ' + utils.html.decodeEntities(matches[1]) + ' ^');
					}
				}); // request errors are silently discarded
				
				// do not process more urls
				break;
			}
			catch (e) {
				// not a valid url
			}
		}
	});
};

@@ -14,19 +14,23 @@
 %0A%0Aconst 
-url
+%7B URL %7D
  = requi
@@ -265,17 +265,15 @@
 j = 
-url.parse
+new URL
 (par
@@ -280,16 +280,17 @@
 ts%5Bi%5D);%0A
+%0A
 %09%09%09%09util

Fix URL parsing