"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = extractPackageFile;
const logger_1 = require("../../../logger");
const array_1 = require("../../../util/array");
const regex_1 = require("../../../util/regex");
const maven_1 = require("../../datasource/maven");
const maven_2 = require("../../versioning/maven");
// https://regex101.com/r/IcOs7P/1
const DISTRIBUTION_URL_REGEX = (0, regex_1.regEx)('^(?:distributionUrl\\s*=\\s*)(?<url>\\S*-(?<version>\\d+\\.\\d+(?:\\.\\d+)?(?:-\\w+)*)-(?<type>bin|all)\\.zip)\\s*$');
const WRAPPER_URL_REGEX = (0, regex_1.regEx)('^(?:wrapperUrl\\s*=\\s*)(?<url>\\S*-(?<version>\\d+\\.\\d+(?:\\.\\d+)?(?:-\\w+)*)(?:.jar))');
function extractVersions(fileContent) {
    const lines = (0, array_1.coerceArray)(fileContent?.split(regex_1.newlineRegex));
    const maven = extractLineInfo(lines, DISTRIBUTION_URL_REGEX) ?? undefined;
    const wrapper = extractLineInfo(lines, WRAPPER_URL_REGEX) ?? undefined;
    return { maven, wrapper };
}
function extractLineInfo(lines, regex) {
    for (const line of lines) {
        if (line.match(regex)) {
            const match = regex.exec(line);
            if (match?.groups) {
                return {
                    url: match.groups.url,
                    version: match.groups.version,
                };
            }
        }
    }
    return null;
}
function extractPackageFile(fileContent) {
    logger_1.logger.trace('maven-wrapper.extractPackageFile()');
    const extractResult = extractVersions(fileContent);
    const deps = [];
    if (extractResult.maven?.version) {
        const maven = {
            depName: 'maven',
            packageName: 'org.apache.maven:apache-maven',
            currentValue: extractResult.maven?.version,
            replaceString: extractResult.maven?.url,
            datasource: maven_1.MavenDatasource.id,
            versioning: maven_2.id,
        };
        deps.push(maven);
    }
    if (extractResult.wrapper?.version) {
        const wrapper = {
            depName: 'maven-wrapper',
            packageName: 'org.apache.maven.wrapper:maven-wrapper',
            currentValue: extractResult.wrapper?.version,
            replaceString: extractResult.wrapper?.url,
            datasource: maven_1.MavenDatasource.id,
            versioning: maven_2.id,
        };
        deps.push(wrapper);
    }
    return deps.length ? { deps } : null;
}
//# sourceMappingURL=extract.js.map