"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 = ['create <id>'];
exports.desc = 'Create a new tile source';
exports.builder = (args) => {
    return args
        .option('type', {
        alias: 't',
        description: 'Tilesource type',
        type: 'string',
        choices: ['tilelive', 'dataset']
    })
        .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', type: 'string' });
};
function handler(params) {
    return __awaiter(this, void 0, void 0, function* () {
        const client = params.client;
        const drivers = yield client.tileSources.drivers();
        const id = params.id;
        try {
            // Handle interactive moce
            if (params.interactive) {
                const answers = yield inquirer.prompt([
                    {
                        type: 'list',
                        name: 'type',
                        message: 'Data source',
                        choices: drivers,
                        default: params.type || 'dataset'
                    },
                    {
                        type: 'input',
                        name: 'source',
                        message: 'TileLive URL',
                        default: params.source,
                        when: ({ type }) => type === 'tilelive'
                    },
                    {
                        type: 'list',
                        name: 'source',
                        message: 'Dataset',
                        choices: listDatasets.bind(null, params.client),
                        default: params.source,
                        when: ({ type }) => type === 'dataset'
                    },
                    {
                        type: 'input',
                        name: 'attribution',
                        message: 'Attribution',
                        default: params.attribution
                    },
                    {
                        type: 'input',
                        name: 'minZoom',
                        message: 'Minimum zoom',
                        default: params.minZoom || 0,
                        validate: val => isNumeric(val) || 'Enter a number'
                    },
                    {
                        type: 'input',
                        name: 'maxZoom',
                        message: 'Maximum zoom',
                        default: params.maxZoom || 18,
                        validate: val => isNumeric(val) || 'Enter a number'
                    },
                    {
                        type: 'confirm',
                        name: 'overrideExtent',
                        message: 'Override auto-calculated map extent',
                        default: params.extent ? !!params.extent.length : false
                    },
                    {
                        type: 'input',
                        name: 'extent',
                        message: 'Map extent (x1 y1 x2 y2) (blank for auto-detect)',
                        validate: val => 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 (!isValidExtent(params.extent)) {
                    throw new Error(`Bad format for extent: specify 'x1 y1 x2 y2' (lng/lat)`);
                }
                extentLngLat = extentFromString(params.extent);
            }
            let tileSource = {
                id: params.id,
                type: params.type,
                source: params.source,
                attribution: params.attribution,
                minZoom: params.minZoom,
                maxZoom: params.maxZoom,
                extentLngLat
            };
            tileSource = yield client.tileSources.create(tileSource);
            utils_1.logObject(tileSource, 'table', ['appId', 'createdAt', 'updatedAt']);
        }
        catch (e) {
            utils_1.logError(e.message);
        }
    });
}
exports.handler = handler;
function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
function isValidExtent(extent) {
    if (!extent || extent.length === 0) {
        return false;
    }
    if (typeof extent === 'string') {
        extent = extent.split(' ');
    }
    if (extent.length !== 4) {
        return false;
    }
    return !extent.find(d => !isNumeric(d));
}
function extentFromString(extent) {
    if (extent === null || extent === undefined) {
        return null;
    }
    if (typeof extent === 'string') {
        extent = extent.split(' ');
    }
    return extent.map(d => parseFloat(d));
}
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=create.js.map