'use strict'
const http = require('http');
const host = 'rpi.titandesign.eu';
exports.GoogleAssistant = (req, res) => {
    let date = req.body.result.parameters['date'];
    let time = '';
    if (req.body.result.parameters['time']) {
        time = req.body.result.parameters['time'];
    }

    callDB(date, time).then((output) => {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({'speech' : output, 'displayText' : output}));
    }).catch((error) => {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({'speech' : error, 'displayText' : error}));
    });

}

function callDB(date, time){
    return new Promise((resolve, reject) => {
        let path = '';
        if (time){
            path = '/api/weathers/average.json?date=' + date + '&time=' + time;
        } else if (!time) {
            path = '/api/weathers/average.json?date=' + date;
        }
        console.log('API Request :' + host + path);
        http.get({host: host, path: path, headers: {accept: "application/vnd.api+json"}}, (res) => {
            let body = '';
            res.on('data', (d) => {body += d;});
            res.on('end', () => {
                let response = JSON.parse(body);
                let temp = response['data'][0]['attributes']['avg_temp'].toFixed(2);
                let hum = response['data'][0]['attributes']['avg_hum'].toFixed(2);
                let press = ((response['data'][0]['attributes']['avg_pres'])/1000).toFixed(2);
		var rain;
                if (response['data'][0]['attributes']['avg_water'].toFixed(2)<=50){
                    rain = 'no';
                } else if (response['data'][0]['attributes']['avg_water'].toFixed(2)>50 && response['data'][0]['attributes']['avg_water'].toFixed(2)<=500){
                    rain = 'light';
                } else if (response['data'][0]['attributes']['avg_water'].toFixed(2)>500){
                    rain = 'heavy';
                } else {rain = '';}
                let index = response['data'][0]['attributes']['avg_uv'].toFixed(2);
                let output = 'It was ' + temp +'°Celsius with ' + hum + '% humidity and air pressure of ' + press + ' kiloPascals. There was ' + rain + ' rain. UV index: ' + index + '. Would you like to get information about weather conditions in different time?';
                console.log(output);
                resolve(output);
            });
            res.on('error', (error) => {
                reject(error);
            });
        });

    });
}