// Expirements - Advanced Chatbot

var fs = require('fs')

function removePunctuation(inputString) {
    return inputString.replace(/[.:,!?—()]/g, '').toLowerCase();
}

function simplify(text, templatename) {
    var template = JSON.parse(fs.readFileSync(templatename).toString())
    var decoded = removePunctuation(text)
    return decoded.split(" ").map((harder) => {
        for (const [key, value] of Object.entries(template.synonymizer)) {
            if (value.includes(harder)) {
                return key
            }
        }
        return harder
    }).join(" ")
}

function answer(question, templatename) {
    var template = JSON.parse(fs.readFileSync(templatename).toString())
    var sQuestion = question.split(' ')
    for (const [key, value] of Object.entries(template.rules)) {
        var tr = true
        value.forEach((rule) => {
            switch(rule[0]) {
                case "contains":
                    if (!(sQuestion.includes(rule[1]))) {
                        tr = false
                    }
                    break
            }
        })
        if (tr) {
            return key
        }
    }
    return template.default
}

function fullAnswer(question, templatename) {
    return answer(simplify(question, templatename), templatename)
}

module.exports = {simplify, answer, fullAnswer}
