"use strict";
/*
 * Copyright 2022, collaboration Factory AG. All rights reserved.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbstractPackageJsonGenerator = void 0;
const path = require("path");
const fs = require("fs");
const utils_1 = require("../utils");
const CplaceVersion_1 = require("./CplaceVersion");
class AbstractPackageJsonGenerator {
    constructor(repositoryDir) {
        this.repositoryDir = repositoryDir;
        this.packageJsonFile = 'package.json';
    }
    /**
     * Generate package.json file.
     */
    generatePackageJson() {
        const filePath = this.getFilePath();
        if (!fs.existsSync(filePath)) {
            const pluginDependencies = this.getPluginDependencies();
            const devDependencies = this.createDevDependencies(pluginDependencies);
            let packageJson = {};
            packageJson.name = this.getPackageName();
            packageJson.version = this.getVersion();
            packageJson.devDependencies = devDependencies;
            this.packageJsonContent = packageJson;
        }
        else {
            // update package name and version
            console.log(`⟲ Updating version and name in package.json ${filePath}`);
            const content = fs.readFileSync(filePath, {
                encoding: 'utf8',
            });
            this.packageJsonContent = JSON.parse(content);
            this.packageJsonContent.name = this.getPackageName();
            this.packageJsonContent.version = this.getVersion();
        }
        this.saveConfig(this.packageJsonContent, filePath);
        console.log(`${utils_1.GREEN_CHECK} updated package.json file in ${filePath}`);
        return filePath;
    }
    getVersion() {
        return CplaceVersion_1.CplaceVersion.toString().toLowerCase();
    }
    createDevDependencies(pluginDependencies) {
        let devDependencies = {};
        // only add plugins from other repositories as npm dependencies,
        // plugins from the current repo should be used directly
        pluginDependencies
            .filter((dependency) => !fs.existsSync(path.resolve(this.repositoryDir, dependency.name)))
            .forEach((dependency) => (devDependencies[`@${dependency.group.replace(/\./g, '-')}/${dependency.name.replace(/\./g, '-')}`] = this.getVersion()));
        return devDependencies;
    }
    saveConfig(jsonObject, filePath) {
        const stringContent = JSON.stringify(jsonObject, null, 2);
        fs.writeFileSync(filePath, stringContent, { encoding: 'utf8' });
        utils_1.debug(`(AbstractPackageJsonGenerator) [${filePath}] package.json content:`);
        utils_1.debug(stringContent);
    }
}
exports.AbstractPackageJsonGenerator = AbstractPackageJsonGenerator;
//# sourceMappingURL=AbstractPackageJsonGenerator.js.map