"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const { Command } = require("commander");
const getRegistry_js_1 = require("../../lib/getRegistry.js");
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const chalk = require("chalk");
exports.build = new Command()
    .name("registry:build")
    .option("-c, --cwd", "Working directory. Deafults to the current working directory", process.cwd())
    .description("builds the registry for components")
    .action((options) => __awaiter(void 0, void 0, void 0, function* () {
    yield buildRegistry(options.cwd);
}));
// Builds the registry for components
const buildRegistry = (cwd) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const registry = (0, getRegistry_js_1.getRegistry)();
        const registryStorePath = path_1.default.join(cwd, "public", "r");
        if (!fs_1.default.existsSync(registryStorePath)) {
            fs_1.default.mkdirSync(registryStorePath, { recursive: true });
        }
        for (const item of registry.items) {
            const componentRegistry = item;
            componentRegistry.files = componentRegistry.files.map(file => {
                const fileSourcePath = path_1.default.join(cwd, file.path);
                const fileContent = fs_1.default.readFileSync(fileSourcePath, "utf-8");
                return Object.assign(Object.assign({}, file), { content: fileContent });
            });
            const fileDestinationPath = path_1.default.join(registryStorePath, `${componentRegistry.name}.json`);
            fs_1.default.writeFileSync(fileDestinationPath, JSON.stringify(componentRegistry, null, 2));
        }
    }
    catch (error) {
        console.log(chalk.red("Error while building registry E:", error.message));
        throw error;
    }
});
