import { existsSync } from 'fs';
import chalk from 'chalk';
import { convertSecretToBase64, createBase64Secret, removeFieldsWithNullishValues } from '../../base/support/index.mjs';
import { applicationTypes, buildToolTypes, getConfigWithDefaults } from '../../../jdl/jhipster/index.mjs';
import { GENERATOR_JHIPSTER } from '../../generator-constants.mjs';
import { loadDeploymentConfig } from '../../base-workspaces/internal/index.mjs';
import { loadDerivedAppConfig } from '../../app/support/index.mjs';
import { loadDerivedPlatformConfig, loadDerivedServerConfig } from '../../server/support/index.mjs';
const { MAVEN } = buildToolTypes;
const { MONOLITH, MICROSERVICE, GATEWAY } = applicationTypes;
export { checkDocker } from '../../docker/support/index.mjs';
export function checkImages() {
    this.log.log('\nChecking Docker images in applications directories...');
    let imagePath = '';
    let runCommand = '';
    this.hasWarning = false;
    this.warningMessage = 'To generate the missing Docker image(s), please run:\n';
    this.appsFolders.forEach((appsFolder, index) => {
        const appConfig = this.appConfigs[index];
        if (appConfig.buildTool === MAVEN) {
            imagePath = this.destinationPath(`${this.directoryPath + appsFolder}/target/jib-cache`);
            runCommand = `./mvnw -ntp -Pprod verify jib:dockerBuild${process.arch === 'arm64' ? ' -Djib-maven-plugin.architecture=arm64' : ''}`;
        }
        else {
            imagePath = this.destinationPath(`${this.directoryPath + appsFolder}/build/jib-cache`);
            runCommand = `./gradlew bootJar -Pprod jibDockerBuild${process.arch === 'arm64' ? ' -PjibArchitecture=arm64' : ''}`;
        }
        if (!existsSync(imagePath)) {
            this.hasWarning = true;
            this.warningMessage += `  ${chalk.cyan(runCommand)} in ${this.destinationPath(this.directoryPath + appsFolder)}\n`;
        }
    });
}
export function generateJwtSecret() {
    if (this.jwtSecretKey === undefined) {
        this.jwtSecretKey = this.jhipsterConfig.jwtSecretKey = createBase64Secret(this.options.reproducibleTests);
    }
}
export function configureImageNames() {
    for (let i = 0; i < this.appsFolders.length; i++) {
        const originalImageName = this.appConfigs[i].baseName.toLowerCase();
        const targetImageName = this.dockerRepositoryName ? `${this.dockerRepositoryName}/${originalImageName}` : originalImageName;
        this.appConfigs[i].targetImageName = targetImageName;
    }
}
export function loadConfigs() {
    this.appConfigs = [];
    this.gatewayNb = 0;
    this.monolithicNb = 0;
    this.microserviceNb = 0;
    const serverPort = 8080;
    const getJhipsterConfig = yoRcPath => this.createStorage(yoRcPath, GENERATOR_JHIPSTER);
    this.log.debug(`Apps folders: ${this.appsFolders}`);
    this.appsFolders.forEach((appFolder, index) => {
        const path = this.destinationPath(`${this.directoryPath + appFolder}`);
        this.log.debug(chalk.red.bold(`App folder ${path}`));
        if (this.fs.exists(`${path}/.yo-rc.json`)) {
            const config = getConfigWithDefaults(removeFieldsWithNullishValues(getJhipsterConfig(`${path}/.yo-rc.json`).getAll()));
            config.composePort = serverPort + index;
            this.log.debug(chalk.red.bold(`${config.baseName} has compose port ${config.composePort} and appIndex ${config.applicationIndex}`));
            loadDerivedAppConfig({ application: config });
            loadDerivedPlatformConfig({ application: config });
            loadDerivedServerConfig({ application: config });
            if (config.applicationType === MONOLITH) {
                this.monolithicNb++;
            }
            else if (config.applicationType === GATEWAY) {
                this.gatewayNb++;
            }
            else if (config.applicationType === MICROSERVICE) {
                this.microserviceNb++;
            }
            this.portsToBind = this.monolithicNb + this.gatewayNb;
            config.appFolder = appFolder;
            this.appConfigs.push(config);
        }
        else {
            throw new Error(`Application '${appFolder}' is not found in the path '${this.directoryPath}'`);
        }
    });
}
export function setClusteredApps() {
    for (let i = 0; i < this.appsFolders.length; i++) {
        for (let j = 0; j < this.clusteredDbApps.length; j++) {
            this.appConfigs[i].clusteredDb = this.appsFolders[i] === this.clusteredDbApps[j];
        }
    }
}
export function loadFromYoRc() {
    loadDeploymentConfig.call(this);
    this.useKafka = false;
    this.usePulsar = false;
    this.useMemcached = false;
    this.useRedis = false;
    loadConfigs.call(this);
    if (this.microserviceNb > 0 || this.gatewayNb > 0) {
        this.deploymentApplicationType = MICROSERVICE;
    }
    else {
        this.deploymentApplicationType = MONOLITH;
    }
    setClusteredApps.call(this);
    if (!this.adminPassword) {
        this.adminPassword = 'admin';
        this.adminPasswordBase64 = convertSecretToBase64(this.adminPassword);
    }
}
