"use strict";
/**
 * Copyright © 2018 Emu Analytics
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = exports.builder = exports.desc = exports.command = void 0;
const utils_1 = require("../../utils");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ora_1 = __importDefault(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';
const 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.builder = builder;
const handler = (p) => __awaiter(void 0, void 0, void 0, function* () {
    if (p.hasOwnProperty('source-srid') && isNaN(p['source-srid'])) {
        (0, utils_1.logError)('--source-srid must be a number');
        process.exit(1);
    }
    if (p.hasOwnProperty('target-srid') && isNaN(p['target-srid'])) {
        (0, utils_1.logError)('--target-srid must be a number');
        process.exit(1);
    }
    const filename = path.basename(p.filePath);
    (0, utils_1.logInfo)(`Uploading file ${filename} ...`);
    const uploadSpinner = (0, ora_1.default)('Uploading').start();
    const ingestingSpinner = (0, ora_1.default)('Ingesting');
    const processingSpinner = (0, ora_1.default)('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();
                    (0, utils_1.logInfo)(`Dataset uploaded with id '${polledUpload.options.datasetId}' (${(0, humanize_plus_1.fileSize)(polledUpload.size)})`);
                    break;
                }
                else {
                    currentSpinner.fail();
                    (0, utils_1.logError)(polledUpload.error.message);
                    (0, utils_1.logDetail)(polledUpload.error.stderr || polledUpload.error.stdout);
                    break;
                }
            }
        }
    }
    catch (e) {
        uploadSpinner.stop();
        ingestingSpinner.stop();
        processingSpinner.stop();
        (0, utils_1.logError)(e);
    }
});
exports.handler = handler;
//# sourceMappingURL=upload.js.map