"use strict";
/*
 * Copyright 2019-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 utils_1 = require("@adpt/utils");
const lodash_1 = require("lodash");
const http_server_types_1 = require("./http_server_types");
/** @public */
function useResolvedFiles(files) {
    const [resolved, setResolved] = core_1.useState(undefined);
    setResolved(() => {
        const done = [];
        for (const f of files) {
            if (http_server_types_1.isFilesResolved(f)) {
                done.push(f);
                continue;
            }
            const image = core_1.callInstanceMethod(f.image, undefined, "image");
            const imgName = image && lodash_1.isObject(image) && lodash_1.isString(image.nameTag) ? image.nameTag : null;
            if (image && !imgName) {
                throw new Error(`Cannot use container image as file source. Image exists but does not have a tag.`);
            }
            if (imgName) {
                done.push(Object.assign({}, f, { image: imgName }));
            }
            else {
                return undefined;
            }
        }
        return done;
    });
    return resolved;
}
exports.useResolvedFiles = useResolvedFiles;
const filesFrom = new utils_1.Dispatcher("Files");
filesFrom.add("local", (fObj) => {
    const dockerCommands = fObj.files
        .map(({ src, dest }) => `COPY ${src} ${dest}`)
        .join("\n");
    return { dockerCommands };
});
filesFrom.add("image", (fObj) => {
    const dockerCommands = fObj.files
        .map(({ src, dest }) => `COPY --from=${fObj.stage} ${src} ${dest}`)
        .join("\n");
    return { dockerCommands, stage: { image: fObj.image, name: fObj.stage } };
});
/** @public */
function useFilesInfo(files) {
    const resolved = useResolvedFiles(files);
    return resolved && resolved.map((f) => filesFrom.dispatch(f));
}
exports.useFilesInfo = useFilesInfo;
/**
 * Returns all `Handle`s referenced by the set of `files`.
 * @public
 */
function fileHandles(files) {
    return files.map((f) => http_server_types_1.isFilesResolved(f) ? null : f.image).filter(utils_1.notNull);
}
exports.fileHandles = fileHandles;
//# sourceMappingURL=files.js.map