"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");
const JSONStream = require("JSONStream");
const moment = require("moment");
const stream_1 = require("stream");
exports.command = ['import <file> [<id>]'];
exports.desc = 'Import an application from JSON';
exports.builder = (args) => {
    return args
        .positional('file', { describe: 'Path to input JSON file', type: 'string' })
        .positional('id', { describe: 'Application id (omit to use id from file)', type: 'string' });
};
function handler({ client, id, file }) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            file = path.resolve(file);
            const now = moment().toISOString();
            const uploadSpinner = ora(`Importing from: ${file}`).start();
            const inputStream = fs.createReadStream(file, { encoding: 'utf8' });
            const parser = JSONStream.parse([true, { emitPath: true }]);
            let resourceCount = 0;
            const writer = new stream_1.Writable({
                objectMode: true,
                write(obj, encoding, callback) {
                    const resourceType = obj.path[0];
                    const resourceIndex = obj.path[1];
                    const resource = obj.value;
                    const resourceEndpoint = get(client, resourceType);
                    if (typeof resource !== 'object' || !resourceEndpoint) {
                        callback(new Error(`Bad file format: ${resourceType}[${resourceIndex}]`));
                    }
                    // Rewrite timestamps
                    if (resource.createdAt) {
                        resource.createdAt = now;
                    }
                    if (resource.updatedAt) {
                        resource.updatedAt = now;
                    }
                    if (id) {
                        // Rewrite application id
                        if (resourceType === 'applications') {
                            resource.id = id;
                        }
                        else {
                            resource.applicationId = id;
                        }
                    }
                    // Create resource j
                    resourceEndpoint
                        .create(resource, { applicationId: resource.applicationId })
                        .then(r => {
                        uploadSpinner.text = `Imported ${resourceType}[${resourceIndex}]`;
                        resourceCount++;
                        callback();
                    })
                        .catch(callback);
                }
            });
            const p = stream_1.pipeline(inputStream, parser, writer, err => {
                if (err) {
                    uploadSpinner.fail();
                    utils_1.logError(err);
                    process.exit(1);
                }
                uploadSpinner.succeed(`Imported ${resourceCount} resource${resourceCount > 1 ? 's' : ''}`);
            });
        }
        catch (e) {
            utils_1.logError(e);
        }
    });
}
exports.handler = handler;
//# sourceMappingURL=import.js.map