"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 tile source';
exports.builder = (args) => {
    return args
        .option('type', {
        alias: 't',
        description: 'Tilesource type',
        type: 'string'
    })
        .option('source', {
        alias: 's',
        description: 'Tilesource source (tilelive URL or dataset ID)',
        type: 'string'
    })
        .option('attribution', { alias: 'a', description: 'Tilesource attribution', type: 'string' })
        .option('minZoom', { alias: 'm', description: 'Minimum zoom', type: 'number' })
        .option('maxZoom', { alias: 'M', description: 'Maximum zoom', type: 'number' })
        .option('extent', { alias: 'e', description: 'Extent x1,y1,x2,y2 (lng/lat)', type: 'array' })
        .option('headers', {
        alias: 'H',
        description: 'Tile HTTP headers (space-separated <name>=<value> pairs)',
        type: 'array'
    })
        .option('interactive', {
        alias: 'i',
        describe: 'Show interactive prompts',
        type: 'boolean',
        default: 'true'
    })
        .positional('id', { describe: 'Tilesource 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;
        const drivers = yield client.tileSources.drivers();
        try {
            let tileSource = yield utils_1.resolveResource(id, client.tileSources);
            // Handle interactive moce
            if (params.interactive) {
                const answers = yield inquirer.prompt([
                    {
                        type: 'list',
                        name: 'type',
                        message: 'Tilesource Type',
                        choices: drivers,
                        default: params.type || tileSource.type
                    },
                    {
                        type: 'input',
                        name: 'source',
                        message: 'TileLive URL',
                        default: params.source || tileSource.source,
                        when: ({ type }) => type === 'tilelive'
                    },
                    {
                        type: 'list',
                        name: 'source',
                        message: 'Dataset',
                        choices: listDatasets.bind(null, params.client),
                        default: params.source || tileSource.source,
                        when: ({ type }) => type !== 'tilelive'
                    },
                    {
                        type: 'input',
                        name: 'attribution',
                        message: 'Attribution',
                        default: params.attribution || tileSource.attribution
                    },
                    {
                        type: 'input',
                        name: 'minZoom',
                        message: 'Minimum zoom',
                        default: params.minZoom || tileSource.minZoom,
                        validate: val => utils_1.isNumeric(val) || 'Enter a number'
                    },
                    {
                        type: 'input',
                        name: 'maxZoom',
                        message: 'Maximum zoom',
                        default: params.maxZoom || tileSource.maxZoom,
                        validate: val => utils_1.isNumeric(val) || 'Enter a number'
                    },
                    {
                        type: 'confirm',
                        name: 'overrideExtent',
                        message: 'Override map extent specfied by dataset',
                        default: params.extent ? !!params.extent.length : !!tileSource.extentLngLat
                    },
                    {
                        type: 'input',
                        name: 'extent',
                        message: 'Map extent (x1 y1 x2 y2) (blank to use extent specified by dataset)',
                        default: utils_1.extentToString(params.extent || tileSource.extentLngLat),
                        validate: val => utils_1.isValidExtent(val) || 'Enter lng/lat bounding box as x1 y1 x2 y2',
                        when: ({ overrideExtent }) => overrideExtent
                    }
                ]);
                params.type = answers.type;
                params.source = answers.source;
                params.attribution = answers.attribution;
                params.minZoom = answers.minZoom;
                params.maxZoom = answers.maxZoom;
                params.extent = answers.overrideExtent ? answers.extent.split(' ') : [];
            }
            // Headers
            let headers;
            if (params.headers) {
                headers = params.headers.reduce((accum, param) => {
                    const [key, value] = param.split('=');
                    if (!key || !value) {
                        throw new Error('Bad format for headers: specify key/value pairs as <header>=<value>');
                    }
                    accum[key] = value;
                    return accum;
                }, {});
            }
            // Extent
            let extentLngLat;
            if (params.extent && params.extent.length === 0) {
                extentLngLat = null;
            }
            else if (params.extent) {
                if (!utils_1.isValidExtent(params.extent)) {
                    throw new Error(`Bad format for extent: specify 'x1 y1 x2 y2' (lng/lat)`);
                }
                extentLngLat = utils_1.extentFromString(params.extent);
            }
            tileSource = yield client.tileSources.update(tileSource.id, {
                id: params.id,
                type: params.type,
                source: params.source,
                attribution: params.attribution,
                headers,
                minZoom: params.minZoom,
                maxZoom: params.maxZoom,
                extentLngLat
            });
            utils_1.logObject(tileSource, 'table', ['appId', 'createdAt', 'updatedAt']);
        }
        catch (e) {
            utils_1.logError(e.message);
        }
    });
}
exports.handler = handler;
function listDatasets(client) {
    return __awaiter(this, void 0, void 0, function* () {
        const datasets = yield client.datasets.list({ sort: 'id' });
        return datasets.map(ds => ds.id);
    });
}
//# sourceMappingURL=update.js.map