"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getConfig = exports.setConfigVersionOnExpression = exports.getConfigFromExpression = exports.getConfigExpressionForProject = void 0;
const codehandler_1 = require("@syftdata/codehandler");
const ts_morph_1 = require("ts-morph");
const STATIC_CONFIG_TYPE = 'StaticConfig';
function getConfigExpressionForProject(project) {
    let syftConfig;
    for (const sourceFile of project.getSourceFiles()) {
        sourceFile.getVariableDeclarations().forEach((variable) => {
            let varialbeType = variable.getType().getText();
            const symbol = variable.getType().getSymbol();
            if (symbol !== undefined) {
                varialbeType = symbol.getEscapedName();
            }
            if (varialbeType !== STATIC_CONFIG_TYPE)
                return;
            syftConfig = variable.getInitializerIfKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression);
        });
        if (syftConfig !== undefined)
            break;
    }
    return syftConfig;
}
exports.getConfigExpressionForProject = getConfigExpressionForProject;
function getConfigFromExpression(expression) {
    const val = {
        projectName: 'test',
        version: '0.0.0'
    };
    expression.getProperties().forEach((property) => {
        if (property instanceof ts_morph_1.PropertyAssignment) {
            const propertyName = property.getSymbolOrThrow().getEscapedName();
            const value = property
                .getInitializerOrThrow()
                .getText()
                .replace(/['"]/g, '');
            if (propertyName === 'version') {
                val[propertyName] = value;
            }
        }
    });
    return val;
}
exports.getConfigFromExpression = getConfigFromExpression;
function setConfigVersionOnExpression(expression, version) {
    expression.getProperties().forEach((property) => {
        if (property instanceof ts_morph_1.PropertyAssignment) {
            const propertyName = property.getSymbolOrThrow().getEscapedName();
            if (propertyName === 'version') {
                property.setInitializer(`'${version}'`);
                return true;
            }
        }
    });
    return false;
}
exports.setConfigVersionOnExpression = setConfigVersionOnExpression;
function getConfig(schemaFolder) {
    const project = (0, codehandler_1.createTSProject)([schemaFolder]);
    const expression = getConfigExpressionForProject(project);
    if (expression === undefined) {
        return;
    }
    return getConfigFromExpression(expression);
}
exports.getConfig = getConfig;
