/**
 * AWS Athena for get historical data
 * @author Manish Yadav
 * @copyright Semusi Technologies PVT LTD
 */
'use strict'
const semusiConfig = require("./../config"),
        Promise = require("bluebird"),
        athena = require("athena-client"),
        client = athena.createClient({
            bucketUri: semusiConfig.athenaBucketURI
        },
        {
            region: semusiConfig.AWS_REGION,
            accessKeyId: semusiConfig.AWS_ACCESS_KEY_ID,
            secretAccessKey: semusiConfig.AWS_SECRET_KEY,
            ACL: 'public-read'
        });

// Execute athena query
/**
 * Execute athena query
 * @param query is string type and has athena query
 * sample:-
 `SELECT
//         data[1].sid as Session_ID,
//         data[1].eventTime as EventTime,
//         data[1].did as DID,
//         element_at(data[1].segment,'action') as ActionName,
//         element_at(data[1].segment,'label') as LabelName
//         FROM awsgluecrawler.pre_prod
//         WHERE appid = '5a0bd4e6c06f824a5291671a'
//         AND data[1].key = 'ShineAll'
//         AND (data[1].eventTime <= 1519084800 AND data[1].eventTime >= 1517443200)`
 */
exports.runAthenaQuery = function(query){
    return new Promise( (resolve, reject) => {
        //try{
            var resultSet = [],
            stream = client.execute(query).toStream(); // execute query
            // read stream data
            stream.on('data', function(record) {
                resultSet.push(record);
            });
            // query end
            stream.on('query_end', function(queryExecution) {
                return resolve(queryExecution);
            });
            // end stream data
            stream.on('end', function() {
                return resolve(resultSet);
            });
            // error while run query
            stream.on('error', function(e) {
                return reject(e);
            })
        // }
        // catch(error){
        //     return reject(error);
        // }
    })
}
