"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 emoji = require("node-emoji");
const table_1 = require("table");
const stringWidth = require('string-width');
const chalk_1 = require("chalk");
const csvStringify = require("csv-stringify/lib/sync");
// tslint:disable-next-line:no-console
exports.log = console.log;
function logError(e) {
    if (typeof e === 'string') {
        exports.log(emoji.emojify(chalk_1.default.bold.red(e)));
    }
    else {
        exports.log(emoji.emojify(chalk_1.default.bold.red(e.message)));
        if (e.error && e.error.message) {
            logDetail(e.error.message);
        }
    }
}
exports.logError = logError;
function logWarning(s) {
    exports.log(emoji.emojify(chalk_1.default.bold.yellow(s)));
}
exports.logWarning = logWarning;
function logInfo(s) {
    exports.log(emoji.emojify(chalk_1.default.bold(s)));
}
exports.logInfo = logInfo;
function logDetail(s) {
    exports.log(emoji.emojify(chalk_1.default.dim(s)));
}
exports.logDetail = logDetail;
function logObject(o, format = 'table', fields = null) {
    if (!o) {
        return logError('Null object');
    }
    if (format === 'table') {
        let data;
        if (Array.isArray(o)) {
            if (o.length === 0) {
                return exports.log('No Items');
            }
            if (typeof o[0] === 'object') {
                const keys = fields || Object.keys(o[0]);
                data = [['', ...keys.map(key => chalk_1.default.bold.green(key))]];
                o.forEach((rowObj, index) => {
                    const row = [index.toString(), ...keys.map(key => formatCell(rowObj[key]))];
                    data.push(row);
                });
            }
            else {
                data = [['', chalk_1.default.bold.green('Value')]];
                o.forEach((rowObj, index) => {
                    const row = [index.toString(), formatCell(rowObj)];
                    data.push(row);
                });
            }
        }
        else {
            data = [
                [chalk_1.default.bold.green('Property'), chalk_1.default.bold.green('Value')],
                ...Object.keys(o).map(key => [key, formatCell(o[key])])
            ];
        }
        const maxWidths = maxColumnWidths(data);
        const columnConfig = maxWidths.map(width => ({ width: Math.min(width, 36), truncate: 200 }));
        // tslint:disable-next-line:no-console
        console.log(table_1.table(data, { columns: columnConfig }));
    }
    else if (format === 'csv') {
        if (!Array.isArray(o)) {
            o = [o];
        }
        exports.log(csvStringify(o, { header: true }));
    }
    else {
        exports.log(JSON.stringify(o, null, 2));
    }
}
exports.logObject = logObject;
// Support functions taken from table module
function maxColumnWidths(rows) {
    if (!rows[0]) {
        throw new Error('Dataset must have at least one row.');
    }
    const columns = new Array(rows[0].length).fill(0);
    rows.forEach(row => {
        const columnWidthIndex = cellWidthIndex(row);
        columnWidthIndex.forEach((valueWidth, index0) => {
            if (columns[index0] < valueWidth) {
                columns[index0] = valueWidth;
            }
        });
    });
    return columns;
}
function cellWidthIndex(cells) {
    return cells.map(value => {
        return stringWidth(value);
    });
}
function formatCell(obj) {
    if (Array.isArray(obj)) {
        return '<array>';
    }
    if (obj === null) {
        return chalk_1.default.grey('null');
    }
    if (typeof obj === 'object') {
        return '<object>';
    }
    return obj.toString().replace(/[^ -~]/g, ' ');
}
/**
 * Query client resource endpoint give an ID or unique prefix
 *
 * @param idOrPrefix Resource ID or a unique prefix.
 * @param endpoint Flo.w client endpoint to query
 */
function resolveResource(idOrPrefix, endpoint, idField = 'id') {
    return __awaiter(this, void 0, void 0, function* () {
        const results = yield endpoint.list({
            [`filter[${idField}]`]: `~${idOrPrefix}`,
            sort: idField
        });
        if (results.length === 0) {
            throw new Error('Not found');
        }
        if (results.length > 1 && results[0].id !== idOrPrefix) {
            throw new Error(`Multiple matches for '${idOrPrefix}': ${results.map(d => d[idField]).join(', ')}`);
        }
        return results[0];
    });
}
exports.resolveResource = resolveResource;
function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
exports.isNumeric = isNumeric;
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));
}
exports.isValidExtent = isValidExtent;
function extentToString(extent) {
    if (!extent || extent.length === 0) {
        return '';
    }
    return extent.map((d) => d.toString()).join(' ');
}
exports.extentToString = extentToString;
function extentFromString(extent) {
    if (extent === null || extent === undefined) {
        return null;
    }
    if (typeof extent === 'string') {
        extent = extent.split(' ');
    }
    return extent.map(d => parseFloat(d));
}
exports.extentFromString = extentFromString;
//# sourceMappingURL=index.js.map