"use strict";
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateSpecModels = exports.validateSpecModel = void 0;
const validate_1 = require("../validate");
/**
 * Validate a server kernelspec model to a client side model.
 */
function validateSpecModel(data) {
    const spec = data.spec;
    if (!spec) {
        throw new Error('Invalid kernel spec');
    }
    validate_1.validateProperty(data, 'name', 'string');
    validate_1.validateProperty(data, 'resources', 'object');
    validate_1.validateProperty(spec, 'language', 'string');
    validate_1.validateProperty(spec, 'display_name', 'string');
    validate_1.validateProperty(spec, 'argv', 'array');
    let metadata = null;
    if (spec.hasOwnProperty('metadata')) {
        validate_1.validateProperty(spec, 'metadata', 'object');
        metadata = spec.metadata;
    }
    let env = null;
    if (spec.hasOwnProperty('env')) {
        validate_1.validateProperty(spec, 'env', 'object');
        env = spec.env;
    }
    return {
        name: data.name,
        resources: data.resources,
        language: spec.language,
        display_name: spec.display_name,
        argv: spec.argv,
        metadata,
        env
    };
}
exports.validateSpecModel = validateSpecModel;
/**
 * Validate a `Kernel.ISpecModels` object.
 */
function validateSpecModels(data) {
    if (!data.hasOwnProperty('kernelspecs')) {
        throw new Error('No kernelspecs found');
    }
    let keys = Object.keys(data.kernelspecs);
    const kernelspecs = Object.create(null);
    let defaultSpec = data.default;
    for (let i = 0; i < keys.length; i++) {
        const ks = data.kernelspecs[keys[i]];
        try {
            kernelspecs[keys[i]] = validateSpecModel(ks);
        }
        catch (err) {
            // Remove the errant kernel spec.
            console.warn(`Removing errant kernel spec: ${keys[i]}`);
        }
    }
    keys = Object.keys(kernelspecs);
    if (!keys.length) {
        throw new Error('No valid kernelspecs found');
    }
    if (!defaultSpec ||
        typeof defaultSpec !== 'string' ||
        !(defaultSpec in kernelspecs)) {
        defaultSpec = keys[0];
        console.warn(`Default kernel not found, using '${keys[0]}'`);
    }
    return {
        default: defaultSpec,
        kernelspecs
    };
}
exports.validateSpecModels = validateSpecModels;
//# sourceMappingURL=validate.js.map