"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 });
const utils_1 = require("../../utils");
const inquirer = require("inquirer");
exports.command = ['update <id>'];
exports.desc = 'Update a dataset';
exports.builder = (args) => {
    return args
        .option('type', { alias: 't', description: 'Dataset type', type: 'string', choices: ['table', 'sql'] })
        .option('source', { alias: 's', description: 'Dataset source', type: 'string' })
        .option('name', { alias: 'n', description: 'Dataset name', type: 'string' })
        .option('description', { alias: 'd', description: 'Dataset description', type: 'string' })
        .option('interactive', {
        alias: 'i',
        describe: 'Show interactive prompts',
        type: 'boolean',
        default: 'true'
    })
        .option('autodetect', { describe: 'Autodetect geometry', type: 'boolean' })
        .option('srid', { describe: 'Geometry SRID (ignored when autodetect=true)', type: 'number' })
        .option('extent', {
        description: 'Geometry extent x1,y1,x2,y2 (lng/lat) (ignored when autodetect=true)',
        type: 'array'
    })
        .positional('id', { describe: 'Dataset id (or unique prefix)', type: 'string' });
};
function handler(params) {
    return __awaiter(this, void 0, void 0, function* () {
        const client = params.client;
        const id = params.id;
        try {
            const ds = yield utils_1.resolveResource(id, client.datasets);
            if (params.interactive) {
                const answers = yield inquirer.prompt([
                    { type: 'input', name: 'name', message: 'Name', default: params.name || ds.name },
                    {
                        type: 'input',
                        name: 'description',
                        message: 'Description',
                        default: params.description || ds.description
                    },
                    {
                        type: 'confirm',
                        name: 'autodetect',
                        message: 'Autodetect geometry?',
                        default: params.hasOwnProperty('autodetect')
                            ? params.autodetect
                            : ds.options && ds.options.hasOwnProperty('autodetect')
                                ? ds.options.autodetect
                                : true
                    },
                    {
                        type: 'input',
                        name: 'srid',
                        message: 'Geometry SRID',
                        default: params.srid || (ds.options && ds.options.srid) || 4326,
                        validate: val => utils_1.isNumeric(val) || 'Enter a number',
                        when: ({ autodetect }) => autodetect === false
                    },
                    {
                        type: 'input',
                        name: 'extent',
                        message: 'Map extent (x1 y1 x2 y2) (in SRID units)',
                        default: utils_1.extentToString(params.extent || (ds.options && ds.options.extent) || [-180, -90, 180, 90]),
                        validate: val => utils_1.isValidExtent(val) || 'Enter lng/lat bounding box as x1 y1 x2 y2',
                        when: ({ autodetect }) => autodetect === false
                    },
                    {
                        type: 'list',
                        name: 'type',
                        message: 'Source type',
                        choices: ['table', 'sql'],
                        default: params.type || ds.type
                    },
                    {
                        type: 'input',
                        name: 'source',
                        message: 'Table name',
                        default: params.source || ds.source,
                        when: ({ type }) => type === 'table'
                    },
                    {
                        type: 'editor',
                        name: 'source',
                        message: 'SQL query',
                        default: params.source || ds.source,
                        when: ({ type }) => type === 'sql'
                    }
                ]);
                params.name = answers.name;
                params.description = answers.description;
                params.autodetect = answers.autodetect;
                params.srid = answers.autodetect ? undefined : answers.srid;
                params.extent = answers.autodetect ? undefined : utils_1.extentFromString(answers.extent);
                params.type = answers.type;
                params.source = answers.source.trim();
            }
            const updatedDs = yield client.datasets.update(ds.id, {
                id: params.id,
                name: params.name,
                description: params.description,
                type: params.type,
                source: params.source,
                options: {
                    autodetect: params.autodetect,
                    srid: params.srid,
                    extent: params.extent
                }
            });
            /* tslint:disable:no-console */
            console.log(updatedDs);
            const geomAttr = updatedDs.attributes.find(attr => attr.isGeometry);
            if (params.format === 'table') {
                utils_1.logObject(updatedDs, 'table', ['appId', 'createdAt', 'updatedAt', 'ownerId', 'attributes', 'options']);
            }
            else {
                utils_1.logObject(updatedDs, 'json');
            }
            if (geomAttr && geomAttr.type === 'geometry' && updatedDs.options.autodetect) {
                utils_1.logError(`Warning: could not auto-detect SRID or extent of field '${geomAttr.attribute}' (query produced no features)`);
                utils_1.logInfo(`Using the following default values: SRID(${geomAttr.srid}), extent: ${utils_1.extentToString(geomAttr.extent)}`);
                utils_1.logInfo(`Re-run with  --auto-detection=false to manually specify values if this is not correct.`);
            }
        }
        catch (e) {
            utils_1.logError(e.message);
        }
    });
}
exports.handler = handler;
//# sourceMappingURL=update.js.map