"use strict";
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());
    });
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.github = void 0;
const axios_1 = require("axios");
const getAxiosClient = ({ baseUrl, org, repo, token }) => {
    return axios_1.default.create(Object.assign({ baseURL: `${baseUrl}/repos/${org}/${repo}` }, (token
        ? {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        }
        : {})));
};
const removeFileExtension = (fileName) => {
    const lastDot = fileName.lastIndexOf('.');
    return lastDot > -1 ? fileName.slice(0, lastDot) : fileName;
};
const cipherRepository = (repositoryClient, path = '') => __awaiter(void 0, void 0, void 0, function* () {
    const basePath = '/contents';
    const cipherTree = {};
    const { data: repository } = yield repositoryClient.get(`${basePath}/${path}`);
    for (const item of repository) {
        if (item.type === 'dir') {
            cipherTree[item.name] = yield cipherRepository(repositoryClient, `${item.path}`);
        }
        else if (item.type === 'file' && item.name.endsWith('.json')) {
            const { data: fileContent } = yield axios_1.default.get(item.download_url, {
                responseType: 'text',
            });
            const nameWithoutExtension = removeFileExtension(item.name);
            cipherTree[nameWithoutExtension] = JSON.parse(fileContent);
        }
    }
    return cipherTree;
});
const github = (_a) => __awaiter(void 0, void 0, void 0, function* () {
    var { baseUrl = 'https://api.github.com' } = _a, rest = __rest(_a, ["baseUrl"]);
    try {
        const axiosClient = getAxiosClient(Object.assign({ baseUrl }, rest));
        return yield cipherRepository(axiosClient);
    }
    catch (e) {
        throw e;
    }
});
exports.github = github;
