import fs from 'fs';
import { convertEntitiesToJDL } from '../converters/json-to-jdl-entity-converter.js';
import { convertServerOptionsToJDL } from '../converters/json-to-jdl-option-converter.js';
import mergeJDLObjects from '../models/jdl-object-merger.js';
import { doesDirectoryExist } from '../utils/file-utils.js';
import { readJSONFile } from './json-file-reader.js';
export default function parseFromDir(dir) {
    if (!dir) {
        throw new Error('The app directory must be passed to read JSON files.');
    }
    if (!doesDirectoryExist(dir)) {
        throw new Error(`The passed directory '${dir}' must exist and must be a directory to read JSON files.`);
    }
    const entityDir = `${dir}/.jhipster`;
    if (!doesDirectoryExist(entityDir)) {
        throw new Error(`'${entityDir}' must exist as a directory.`);
    }
    const entities = new Map();
    const files = fs.readdirSync(entityDir);
    files.forEach(file => {
        if (file.endsWith('.json')) {
            const entityName = file.slice(0, file.length - 5);
            try {
                entities.set(entityName, readJSONFile(`${entityDir}/${file}`));
            }
            catch (error) {
            }
        }
    });
    const applicationOptions = readJSONFile(`${dir}/.yo-rc.json`)['generator-begcode'];
    const jdlObject = convertServerOptionsToJDL(applicationOptions);
    const convertedJDLObject = convertEntitiesToJDL(entities);
    return mergeJDLObjects(jdlObject, convertedJDLObject);
}
