<commit_before>'use strict'

const request = require('request');
const rp = require('request-promise');

const colors = ['#1c4fff', '#e84778', '#ffc229', '#1ae827', '#5389ff'];

module.exports = function (req, res, next) {
  var botPayload = {};
  botPayload.username = 'Gethuman Bot';
  botPayload.channel = req.body.channel_id;

  var textInput = (req.body.text) ? req.body.text : '';
  if (textInput) {
      summonQuestionResponse(textInput, botPayload, res);
  } else {
      botPayload.text = "Tell me your customer service issue.";
      botPayload.icon_emoji = ':question:';
      send(botPayload, function (error, status, body) {
        if (error) {
          return next(error);
        } else if (status !== 200) {
          return next(new Error('Incoming WebHook: ' + status + ' ' + body));
        } else {
          return res.status(200).end();
      }
      });
  };
}

function send (payload, callback) {
  var path = process.env.INCOMING_WEBHOOK_PATH;
  var uri = 'https://hooks.slack.com/services/' + path;

  request({
    uri: uri,
    method: 'POST',
    body: JSON.stringify(payload)
  }, function (error, response, body) {
    if (error) {
      return callback(error);
    }
    callback(null, response.statusCode, body);
  });
}

function summonQuestionResponse(textInput, botPayload, res) {
    var questions = [];
    var companyIDs = [];
    var guideIDs = [];
    var companyObjects = [];
    var companyTable = {};
    var guideObjects = [];
    var guideTable = {};

    let filters = {
        type: 'question',
        isGuide: true
    };
    let limit = 5;
    request('https://api.gethuman.co/v3/posts/search?match='
            + encodeURIComponent(textInput)
            + '&limit='
            + limit
            + '&filterBy='
            + encodeURIComponent(JSON.stringify(filters))
            , function (error, response, body) {
        if (!error && response.statusCode == 200) {
            questions = JSON.parse(body);
            if (questions && questions.length) {
                for (let i = 0; i < questions.length; i++) {
                    companyIDs.push(questions[i].companyId);
                    guideIDs.push(questions[i].guideId);
                };
                request('https://api.gethuman.co/v3/companies?where='
                    + encodeURIComponent(JSON.stringify({ _id: { $in: companyIDs }}))
                    , function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                        companyObjects = JSON.parse(body);
                        for (let i = 0; i < companyObjects.length; i++) {
                            companyTable[companyObjects[i]._id] = companyObjects[i]
                        };
                        request('https://api.gethuman.co/v3/guides?where='
                            + encodeURIComponent(JSON.stringify({ _id: { $in: guideIDs }}))
                            , function (error, response, body) {
                            if (!error && response.statusCode == 200) {
                                guideObjects = JSON.parse(body);
                                for (let i = 0; i < guideObjects.length; i++) {
                                    guideTable[guideObjects[i]._id] = guideObjects[i]
                                };
                                // attach Companies and Guides to Questions
                                for (var i = 0; i < questions.length; i++) {
                                    let cID = questions[i].companyId;
                                    questions[i].company = companyTable[cID];
                                    let gID = questions[i].guideId;
                                    questions[i].guide = guideTable[gID];
                                };
                                prepareQuestionsPayload(questions, botPayload, res);
                            } else if (error) {
                            console.log(error);
                          }
                        });
                    } else if (error) {
                    console.log(error);
                  }
                });
            } else {
                // console.log("Received no results from Questions API for input: " + textInput);
                summonCompanyResponse(textInput, botPayload, res);
            };
        } else if (error) {
            console.log(error);
        }
    })
};

// first target to Promise-ify
function summonCompanyResponse(textInput, botPayload, res) {
    var companies = [];
    // request('https://api.gethuman.co/v3/companies/search?limit=5&match=' + encodeURIComponent(textInput), function (error, response, body) {
    //     if (!error && response.statusCode == 200) {
    //         companies = JSON.parse(body);
    //         if (companies && companies.length) {
    //             prepareCompaniesPayload(companies, botPayload, res);
    //         } else {
    //             prepareNothingFoundPayload(botPayload, res);
    //         };
    //     } else if (error) {
    //       console.log(error);
    //     }
    // })
    rp('https://api.gethuman.co/v3/companies/search?limit=5&match=' + encodeURIComponent(textInput))
    .then(function (htmlString) {<commit_msg>A terrible misuse of Promises<commit_after>'use strict'

const request = require('request');
const rp = require('request-promise');

const colors = ['#1c4fff', '#e84778', '#ffc229', '#1ae827', '#5389ff'];

module.exports = function (req, res, next) {
  var botPayload = {};
  botPayload.username = 'Gethuman Bot';
  botPayload.channel = req.body.channel_id;

  var textInput = (req.body.text) ? req.body.text : '';
  if (textInput) {
      summonQuestionResponse(textInput, botPayload, res);
  } else {
      botPayload.text = "Tell me your customer service issue.";
      botPayload.icon_emoji = ':question:';
      send(botPayload, function (error, status, body) {
        if (error) {
          return next(error);
        } else if (status !== 200) {
          return next(new Error('Incoming WebHook: ' + status + ' ' + body));
        } else {
          return res.status(200).end();
      }
      });
  };
}

function send (payload, callback) {
  var path = process.env.INCOMING_WEBHOOK_PATH;
  var uri = 'https://hooks.slack.com/services/' + path;

  request({
    uri: uri,
    method: 'POST',
    body: JSON.stringify(payload)
  }, function (error, response, body) {
    if (error) {
      return callback(error);
    }
    callback(null, response.statusCode, body);
  });
}

function summonQuestionResponse(textInput, botPayload, res) {
    var questions = [];
    var companyIDs = [];
    var guideIDs = [];
    var companyObjects = [];
    var companyTable = {};
    var guideObjects = [];
    var guideTable = {};

    let filters = {
        type: 'question',
        isGuide: true
    };
    let limit = 5;

    rp('https://api.gethuman.co/v3/posts/search?match='
        + encodeURIComponent(textInput)
        + '&limit='
        + limit
        + '&filterBy='
        + encodeURIComponent(JSON.stringify(filters)))
    .then(function (htmlString) {
        questions = JSON.parse(htmlString);
        if (questions && questions.length) {
            for (let i = 0; i < questions.length; i++) {
                companyIDs.push(questions[i].companyId);
                guideIDs.push(questions[i].guideId);
            };
            rp('https://api.gethuman.co/v3/companies?where='
                + encodeURIComponent(JSON.stringify({ _id: { $in: companyIDs }})))
            .then(function (htmlString) {
                companyObjects = JSON.parse(htmlString);
                for (let i = 0; i < companyObjects.length; i++) {
                    companyTable[companyObjects[i]._id] = companyObjects[i]
                };
                // final request
                rp('https://api.gethuman.co/v3/guides?where='
                    + encodeURIComponent(JSON.stringify({ _id: { $in: guideIDs }})))
                .then(function (htmlString) {
                    guideObjects = JSON.parse(body);
                    for (let i = 0; i < guideObjects.length; i++) {
                        guideTable[guideObjects[i]._id] = guideObjects[i]
                    };
                    for (var i = 0; i < questions.length; i++) {
                        let cID = questions[i].companyId;
                        questions[i].company = companyTable[cID];
                        let gID = questions[i].guideId;
                        questions[i].guide = guideTable[gID];
                    };
                    prepareQuestionsPayload(questions, botPayload, res);
                })
                .catch(function (err) {
                    console.log(err);
                });
            })
            .catch(function (err) {
                console.log(err);
            });
        } else {
            console.log("Received no results from Questions API for input: " + textInput);
            summonCompanyResponse(textInput, botPayload, res);
        };
    })
    .catch(function (err) {
        console.log(err);
    });

    // ---- original request -----
    // request('https://api.gethuman.co/v3/posts/search?match='
    //         + encodeURIComponent(textInput)
    //         + '&limit='
    //         + limit
    //         + '&filterBy='
    //         + encodeURIComponent(JSON.stringify(filters))
    //         , function (error, response, body) {
    //     if (!error && response.statusCode == 200) {
    //         questions = JSON.parse(body);
    //         if (questions && questions.length) {
    //             for (let i = 0; i < questions.length; i++) {
    //                 companyIDs.push(questions[i].companyId);
    //                 guideIDs.push(questions[i].guideId);
    //             };
    //             request('https://api.gethuman.co/v3/companies?where='
    //                 + encodeURIComponent(JSON.stringify({ _id: { $in: companyIDs }}))
    //                 , function (error, response, body) {
    //                 if (!error && response.statusCode == 200) {
    //                     companyObjects = JSON.parse(body);
    //                     for (let i = 0; i < companyObjects.length; i++) {
    //                         companyTable[companyObjects[i]._id] = companyObjects[i]
    //                     };
    //                     request('https://api.gethuman.co/v3/guides?where='
    //                         + encodeURIComponent(JSON.stringify({ _id: { $in: guideIDs }}))
    //                         , function (error, response, body) {
    //                         if (!error && response.statusCode == 200) {
    //                             guideObjects = JSON.parse(body);
    //                             for (let i = 0; i < guideObjects.length; i++) {
    //                                 guideTable[guideObjects[i]._id] = guideObjects[i]
    //                             };
    //                             // attach Companies and Guides to Questions
    //                             for (var i = 0; i < questions.length; i++) {
    //                                 let cID = questions[i].companyId;
    //                                 questions[i].company = companyTable[cID];
    //                                 let gID = questions[i].guideId;
    //                                 questions[i].guide = guideTable[gID];
    //                             };
    //                             prepareQuestionsPayload(questions, botPayload, res);
    //                         } else if (error) {
    //                         console.log(error);
    //                       }
    //                     });
    //                 } else if (error) {
    //                 console.log(error);
    //               }
    //             });
    //         } else {
    //             // console.log("Received no results from Questions API for input: " + textInput);
    //             summonCompanyResponse(textInput, botPayload, res);
    //         };
    //     } else if (error) {
    //         console.log(error);
    //     }
    // })
    // --------------------------------
};

// first target to Promise-ify
function summonCompanyResponse(textInput, botPayload, res) {
    var companies = [];
    rp('https://api.gethuman.co/v3/companies/search?limit=5&match=' + encodeURIComponent(textInput))
    .then(function (htmlString) {
{'fraction_non_alphanumeric': 0.13894923163569073, 'fraction_numerical': 0.007884785582106365, 'mean_word_length': 1.4536123174101856, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 3, 'https://': 14, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6571458', 'n_tokens_mistral': 3444, 'n_tokens_neox': 3305, 'n_words': 663}