"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 path = require("path");
const fs = require("fs");
const get = require("lodash.get");
const ora = require("ora");
exports.command = ['export <file> <id>'];
exports.desc = 'Export an application to JSON';
exports.builder = (args) => {
    return args
        .positional('file', { describe: 'Path to output JSON file', type: 'string' })
        .positional('id', { describe: 'Application id (or unique prefix)', type: 'string' });
};
function handler({ client, id, file }) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const app = yield utils_1.resolveResource(id, client.applications);
            file = path.resolve(file);
            const uploadSpinner = ora(`Exporting application: ${app.name}`).start();
            const outputStream = fs.createWriteStream(file, { encoding: 'utf8' });
            outputStream.on('error', err => {
                uploadSpinner.fail();
                utils_1.logError(err);
                process.exit(1);
            });
            outputStream.write('{\n');
            const resourceTypes = [
                'applications',
                'apiKeys',
                'appconfig',
                'databases',
                'datasets',
                'styles',
                'tileSources',
                'auth.users'
            ];
            for (const resourceType of resourceTypes) {
                const resourceEndpoint = get(client, resourceType);
                const appIdKey = resourceType === 'applications' ? 'id' : 'applicationId';
                const list = yield resourceEndpoint.list({ filter: { [appIdKey]: app.id } });
                outputStream.write(`"${resourceType}": ${JSON.stringify(list, null, 2)},\n`);
            }
            outputStream.write('}\n');
            outputStream.end();
            uploadSpinner.succeed();
        }
        catch (e) {
            utils_1.logError(e);
        }
    });
}
exports.handler = handler;
//# sourceMappingURL=export.js.map