"use strict";
/*
 * Copyright 2018-2020 Unbounded Systems, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@adpt/core");
const common_1 = require("../common");
const Resource_1 = require("./Resource");
const resourceInfo = new Map();
function getResourceInfo(kind) {
    const info = resourceInfo.get(kind);
    if (!info)
        throw new Error(`Request for ResourceInfo for unknown kind: ${kind}`);
    return info;
}
exports.getResourceInfo = getResourceInfo;
function registerResourceKind(info) {
    const old = resourceInfo.get(info.kind);
    if (old !== undefined)
        throw new Error(`Attempt to register duplicate kind "${info.kind}"`);
    resourceInfo.set(info.kind, info);
}
exports.registerResourceKind = registerResourceKind;
exports.resourceIdToName = common_1.makeResourceName(/[^a-z-]/g, 63);
const deployIDToLabelInner = common_1.makeResourceName(/[^a-z0-9-]/g, 63);
exports.deployIDToLabel = (id) => deployIDToLabelInner(id, "", id);
function resourceElementToName(elem, deployID) {
    if (!Resource_1.isResourceFinalElement(elem))
        throw new Error("Can only compute name of Resource elements");
    if (!core_1.isMountedElement(elem))
        throw new Error("Can only compute name of mounted elements");
    return exports.resourceIdToName(elem.props.key, elem.id, deployID);
}
exports.resourceElementToName = resourceElementToName;
exports.labelKey = (id) => `adaptjs.org/${id}`;
function makeManifest(elem, deployID) {
    if (!core_1.isMountedElement(elem))
        throw new Error("Can only create manifest for mounted elements!");
    const name = resourceElementToName(elem, deployID);
    const ret = {
        apiVersion: elem.props.apiVersion || "v1",
        kind: elem.props.kind,
        metadata: Object.assign({}, elem.props.metadata, { name }),
        spec: elem.props.spec
    };
    if (ret.metadata.annotations === undefined)
        ret.metadata.annotations = {};
    const labels = ret.metadata.labels;
    ret.metadata.labels = Object.assign({}, (labels ? labels : {}), { [exports.labelKey("name")]: name, [exports.labelKey("deployID")]: exports.deployIDToLabel(deployID) });
    ret.metadata.annotations[exports.labelKey("name")] = elem.id;
    ret.metadata.annotations[exports.labelKey("deployID")] = deployID;
    return ret;
}
exports.makeManifest = makeManifest;
//# sourceMappingURL=manifest_support.js.map