"use strict";
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
Object.defineProperty(exports, "__esModule", { value: true });
const api_1 = require("./api");
const path_1 = require("path");
const cmp_1 = require("@cocalc/util/cmp");
async function getContents(githubOrg, githubRepo, segments) {
    if (!githubRepo) {
        // get all repos attached to an org
        const listing = await (0, api_1.repos)(githubOrg);
        listing.sort((0, cmp_1.field_cmp)("mtime"));
        listing.reverse();
        return { listing };
    }
    switch (segments[0]) {
        case undefined:
        case "tree":
            // directory listing
            const response = await (0, api_1.contents)(githubOrg, githubRepo, segments);
            if (response["name"] != null) {
                // it's a file rather than a directory
                throw Error("not implemented");
            }
            const branch = segments[0] == null
                ? await (0, api_1.defaultBranch)(githubOrg, githubRepo)
                : segments[1];
            const listing = [];
            for (const file of response) {
                const isdir = file.type == "dir";
                let url;
                if (isdir) {
                    if (segments[0] == null) {
                        url = `/github/${githubOrg}/${githubRepo}/${(0, path_1.join)("tree", branch, ...segments, file.name)}`;
                    }
                    else {
                        url = `/github/${githubOrg}/${githubRepo}/${(0, path_1.join)(...segments, file.name)}`;
                    }
                }
                else {
                    if (segments[0] == null) {
                        url = `/github/${githubOrg}/${githubRepo}/${(0, path_1.join)("blob", branch, ...segments, file.name)}`;
                    }
                    else {
                        url = `/github/${githubOrg}/${githubRepo}/${(0, path_1.join)("blob", segments[1], ...segments.slice(2), file.name)}`;
                    }
                }
                listing.push({
                    url,
                    name: file.name,
                    isdir,
                    ...(file.type == "file" ? { size: file.size } : undefined),
                });
            }
            return { isdir: true, listing };
            break;
        case "blob":
            const content = await (0, api_1.rawText)(githubOrg, githubRepo, segments);
            return { content, size: content.length };
        default:
            throw Error("not implemented");
    }
}
exports.default = getContents;
//# sourceMappingURL=get-contents.js.map