"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractTerraformKubernetesResource = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const logger_1 = require("../../../../logger");
const regex_1 = require("../../../../util/regex");
const util_1 = require("../util");
function extractTerraformKubernetesResource(startingLine, lines, resourceType) {
    let lineNumber = startingLine;
    const deps = [];
    /**
     * Iterates over all lines of the resource to extract the relevant key value pairs,
     * e.g. the chart name for helm charts or the terraform_version for tfe_workspace
     */
    let braceCounter = 0;
    let inContainer = -1;
    do {
        // istanbul ignore if
        if (lineNumber > lines.length - 1) {
            logger_1.logger.debug(`Malformed Terraform file detected.`);
        }
        const line = lines[lineNumber];
        // istanbul ignore else
        if (is_1.default.string(line)) {
            // `{` will be counted with +1 and `}` with -1. Therefore if we reach braceCounter == 0. We have found the end of the terraform block
            const openBrackets = (line.match((0, regex_1.regEx)(/\{/g)) ?? []).length;
            const closedBrackets = (line.match((0, regex_1.regEx)(/\}/g)) ?? []).length;
            braceCounter = braceCounter + openBrackets - closedBrackets;
            if (line.match((0, regex_1.regEx)(/^\s*(?:init_)?container(?:\s*\{|$)/s))) {
                inContainer = braceCounter;
            }
            else if (braceCounter < inContainer) {
                inContainer = -1;
            }
            const managerData = {
                terraformDependencyType: 'resource',
                resourceType,
            };
            const dep = {
                managerData,
            };
            const kvMatch = util_1.keyValueExtractionRegex.exec(line);
            if (kvMatch?.groups && inContainer > 0) {
                switch (kvMatch.groups.key) {
                    case 'image':
                        managerData[kvMatch.groups.key] = kvMatch.groups.value;
                        managerData.sourceLine = lineNumber;
                        deps.push(dep);
                        break;
                    default:
                        /* istanbul ignore next */
                        break;
                }
            }
        }
        else {
            // stop - something went wrong
            braceCounter = 0;
            inContainer = -1;
        }
        lineNumber += 1;
    } while (braceCounter !== 0);
    // remove last lineNumber addition to not skip a line after the last bracket
    lineNumber -= 1;
    return { lineNumber, dependencies: deps };
}
exports.extractTerraformKubernetesResource = extractTerraformKubernetesResource;
//# sourceMappingURL=kubernetes.js.map