"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 fs = require("fs");
const path = require("path");
const ora = require("ora");
const humanize_plus_1 = require("humanize-plus");
const POLL_INTERVAL = 1000;
exports.command = ['upload <filePath>', '$0'];
exports.desc = 'Upload a geospatial data file';
exports.builder = (y) => {
    return y
        .option('i', {
        alias: 'id',
        describe: 'Dataset id',
        type: 'string'
    })
        .option('n', {
        alias: 'name',
        describe: 'Dataset name',
        type: 'string'
    })
        .option('d', {
        alias: 'description',
        describe: 'Dataset description',
        type: 'string'
    })
        .option('a', {
        alias: 'attribution',
        describe: 'Tiles source attribution',
        type: 'string'
    })
        .option('source-srid', {
        describe: 'Source SRID (default auto-detected from source)',
        type: 'number'
    })
        .option('target-srid', {
        describe: 'Target SRID (default auto-detected from source)',
        number: true,
        type: 'number'
    })
        .option('schema', {
        describe: `Database schema (defaults to 'public' if not specified)`,
        type: 'string'
    })
        .positional('filePath', {
        describe: 'Path to file to upload',
        type: 'string'
    });
};
exports.handler = (p) => __awaiter(void 0, void 0, void 0, function* () {
    if (p.hasOwnProperty('source-srid') && isNaN(p['source-srid'])) {
        utils_1.logError('--source-srid must be a number');
        process.exit(1);
    }
    if (p.hasOwnProperty('target-srid') && isNaN(p['target-srid'])) {
        utils_1.logError('--target-srid must be a number');
        process.exit(1);
    }
    const filename = path.basename(p.filePath);
    utils_1.logInfo(`Uploading file ${filename} ...`);
    const uploadSpinner = ora('Uploading').start();
    const ingestingSpinner = ora('Ingesting');
    const processingSpinner = ora('Processing');
    try {
        const stream = fs.createReadStream(p.filePath);
        // Start the upload
        const upload = yield p.client.uploads.upload({
            data: stream,
            filename,
            datasetId: p.id,
            datasetName: p.name,
            datasetDescription: p.description,
            attribution: p.attribution,
            sourceSrid: p['source-srid'],
            targetSrid: p['target-srid'],
            schema: p.schema
        });
        const uploadId = upload.id;
        // Function to resolve after an interval of time
        const delay = (interval) => {
            return new Promise((resolve, reject) => {
                setTimeout(resolve, interval);
            });
        };
        // Poll for status changes
        let polledUpload;
        let currentStatus = upload.status;
        let currentSpinner = uploadSpinner;
        while (1) {
            yield delay(POLL_INTERVAL);
            polledUpload = yield p.client.uploads.get(uploadId);
            if (polledUpload.status !== currentStatus) {
                currentStatus = polledUpload.status;
                if (currentStatus === 'ingesting') {
                    uploadSpinner.succeed();
                    currentSpinner = ingestingSpinner;
                    currentSpinner.start();
                }
                else if (currentStatus === 'processing') {
                    uploadSpinner.succeed();
                    ingestingSpinner.start();
                    ingestingSpinner.succeed();
                    currentSpinner = processingSpinner;
                    currentSpinner.start();
                }
                else if (currentStatus === 'done') {
                    uploadSpinner.succeed();
                    ingestingSpinner.succeed();
                    processingSpinner.succeed();
                    utils_1.logInfo(`Dataset uploaded with id '${polledUpload.options.datasetId}' (${humanize_plus_1.fileSize(polledUpload.size)})`);
                    break;
                }
                else {
                    currentSpinner.fail();
                    utils_1.logError(polledUpload.error.message);
                    utils_1.logDetail(polledUpload.error.stderr || polledUpload.error.stdout);
                    break;
                }
            }
        }
    }
    catch (e) {
        uploadSpinner.stop();
        ingestingSpinner.stop();
        processingSpinner.stop();
        utils_1.logError(e);
    }
});
//# sourceMappingURL=upload.js.map