'use strict'

module.exports = class AiService {
    constructor(BL) {
        this.AiApiHostname = 'api.api.ai';
        this.AiApiToken = (process.env.Ai_Api_Token || 'fac7152f144f4980a9632ee7b52cb1ef');
        this.https = require('https');
        this.businessLogic = BL;

    }

    analyzeRequest(senderId, text) {
        var options = {
            hostname: this.AiApiHostname,
            path: '/v1/query/?query=' + encodeURIComponent(text) + '&v=20150910&sessionId=1&lang=en',
            port: 443,
            //This is the only line that is new. `headers` is an object with the headers to request
            headers: {
                'Authorization': 'Bearer ' + this.AiApiToken,
                'Content-type': 'application/json; charset=utf-8'
            }
        };

        var callback = (response) => {

            var str = ''
            response.on('data', (chunk) => {
                str += chunk;
            });

            response.on('end', () => {

                var jsonRes = JSON.parse(str);

                this.businessLogic.analyzeRequestResultHandler(senderId, jsonRes);

            });
        }

        var req = this.https.request(options, callback);
        req.end();
    }
}