import * as _ from 'lodash-es';
import { formatDocAsJavaDoc } from '../../server/support/doc.mjs';
const doesTheEnumValueHaveACustomValue = enumValue => {
    return enumValue.includes('(');
};
const getCustomValuesState = enumValues => {
    const state = {
        withoutCustomValue: 0,
        withCustomValue: 0,
    };
    enumValues.forEach(enumValue => {
        if (doesTheEnumValueHaveACustomValue(enumValue)) {
            state.withCustomValue++;
        }
        else {
            state.withoutCustomValue++;
        }
    });
    return {
        withoutCustomValues: state.withCustomValue === 0,
        withSomeCustomValues: state.withCustomValue !== 0 && state.withoutCustomValue !== 0,
        withCustomValues: state.withoutCustomValue === 0,
    };
};
const getEnums = (enums, customValuesState, comments) => {
    if (customValuesState.withoutCustomValues) {
        return enums.map(enumValue => ({
            name: enumValue,
            value: enumValue,
            comment: comments && comments[enumValue] && formatDocAsJavaDoc(comments[enumValue], 4),
        }));
    }
    return enums.map(enumValue => {
        if (!doesTheEnumValueHaveACustomValue(enumValue)) {
            return {
                name: enumValue.trim(),
                value: enumValue.trim(),
                comment: comments && comments[enumValue] && formatDocAsJavaDoc(comments[enumValue], 4),
            };
        }
        const matched = /\s*(.+?)\s*\((.+?)\)/.exec(enumValue);
        return {
            name: matched[1],
            value: matched[2],
            comment: comments && comments[matched[1]] && formatDocAsJavaDoc(comments[matched[1]], 4),
        };
    });
};
const extractEnumInstance = field => {
    const fieldType = field.fieldType;
    return _.lowerFirst(fieldType);
};
const extractEnumEntries = field => {
    return field.fieldValues.split(',').map(fieldValue => fieldValue.trim());
};
export const getEnumInfo = (field, clientRootFolder) => {
    field.enumInstance = extractEnumInstance(field);
    const enums = extractEnumEntries(field);
    const customValuesState = getCustomValuesState(enums);
    return {
        enumName: field.fieldType,
        javadoc: field.fieldTypeDocumentation && formatDocAsJavaDoc(field.fieldTypeDocumentation),
        enumInstance: field.enumInstance,
        enums,
        ...customValuesState,
        enumValues: getEnums(enums, customValuesState, field.fieldValuesJavadocs),
        clientRootFolder: clientRootFolder ? `${clientRootFolder}-` : '',
    };
};
