"use strict";
/**
 * Copyright © 2018 Emu Analytics
 */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = exports.builder = exports.desc = exports.command = void 0;
const utils_1 = require("../../utils");
exports.command = ['query <id>'];
exports.desc = 'Query a dataset';
const builder = (args) => {
    return args
        .option('limit', { alias: 'n', type: 'number', default: 100, describe: 'Limit to n results' })
        .option('offset', {
        alias: ['s', 'skip'],
        type: 'number',
        default: 0,
        describe: 'Start list at offset n'
    })
        .option('query', { alias: ['q'], type: 'string', default: '{}', describe: 'JSON-formatted query' })
        .option('explain', {
        alias: ['x'],
        type: 'boolean',
        default: false,
        describe: 'Explain the generated query'
    })
        .option('explain-analyze', {
        alias: ['xx', 'explain-analyse'],
        type: 'boolean',
        default: false,
        describe: 'Explain and analyze the generated query'
    })
        .option('params', {
        alias: ['p'],
        type: 'array',
        describe: 'One or more query parameters in form <name>=<value>'
    })
        .positional('id', { describe: 'Dataset id (or unique prefix)', type: 'string' });
};
exports.builder = builder;
function handler({ client, id, format, offset, limit, query, explain, explainAnalyze, params }) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const ds = yield (0, utils_1.resolveResource)(id, client.datasets);
            // Query
            const jsonQuery = JSON.parse(query);
            jsonQuery.limit = limit;
            jsonQuery.offset = offset;
            // Query params
            let keyValueParams = {};
            try {
                if (params) {
                    keyValueParams = params.reduce((accum, param) => {
                        const [key, value] = param.split('=');
                        accum[key] = value;
                        return accum;
                    }, {});
                }
            }
            catch (e) {
                throw new Error('Bad format for params: specify key/value pairs as <key>=<value>');
            }
            const queryDefinition = Object.assign(Object.assign({ datasetId: ds.id }, jsonQuery), { format: format === 'table' ? 'json' : format || 'json', params: Object.assign(Object.assign({}, keyValueParams), { explain: explainAnalyze ? 'analyze' : explain ? true : false }) });
            const queryResults = yield client.datasets.query(queryDefinition);
            if (format === 'csv') {
                (0, utils_1.log)(queryResults);
            }
            else {
                (0, utils_1.logObject)(queryResults, format);
            }
        }
        catch (e) {
            (0, utils_1.logError)(e);
        }
    });
}
exports.handler = handler;
//# sourceMappingURL=query.js.map