var typofix = require("typofix"); import { Helper } from './Core'; class replaceableString { str: string; constructor(s) { this.str = s; } replaceAll(search, replacement) { this.str = this.str.split(search).join(replacement); return this; } get() { return this.str; } } export class Matcher { //var dictionary = new Typo("en_US"); static spellCorrect(s) { //punctuation var words = s.split(" "); for (var x = 0; x < words.length; x++) { if (words[x].substring(0, 1) == "<") continue; var array_of_suggestions = typofix.suggest(words[x]); //var array_of_suggestions = []; if (array_of_suggestions.length > 0) { var m = new replaceableString(s); s = m.replaceAll(words[x], array_of_suggestions[0]).get(); } } return s; } static spellCheck(s) { var correct = this.spellCorrect(s); if (s != correct) { return correct; } return null; } static getSpellChecked(matches, text, userId, botId) { var spellCheckedMatch = null; var regexResult = null; var check = Matcher.spellCheck(text); if (check) { matches.forEach(m => { if (spellCheckedMatch) return; regexResult = Matcher.matchTextToCommand(m, check, userId, botId); if (regexResult) { spellCheckedMatch = check; } }); } return { spellCheckedMatch: spellCheckedMatch, regexResult: regexResult }; } static preprocessRegex(match, botUserId) { var m = new replaceableString(match); return ( "^" + m .replaceAll("$me", "____me____") .replaceAll("?", "\\?") .replaceAll("+", "\\+") .replaceAll("*", ".*") .replaceAll("(", "(?:") .replaceAll("____me____", "<@" + botUserId + ">") .get() + "$" ); } static matchTextToCommand(command, text, botUserId, botId) { var r = Matcher.preprocessRegex(command, botUserId); var p = Helper.getNamedParams(r); var regexResult = text.match(p.text); if (regexResult) { regexResult.parameters = {}; Helper.setParametersOnObject(regexResult.parameters, p, regexResult, botId); } return regexResult; } static findMatchFromListOfCommands(commands, userId, text, botId) { var match = null; var regexResult = null; Matcher.registerCommands(commands); commands.forEach(command => { if (match) return; regexResult = this.matchTextToCommand(command, text, userId, botId); if (regexResult) { match = command; } }); return { match: match, regexResult: regexResult }; } static registerCommands(commands) { commands.forEach(command => { typofix.pushNewWords(command.replace(/[^\w\s]/gi, "")); }); } } // //for testing // exports.registerCommands = registerCommands; // exports.replaceableString = replaceableString; // exports.textToCommand = matchTextToCommand; // exports.get = findMatchFromListOfCommands; // exports.getSpellChecked = getSpellChecked;