"use strict";
/*
 * Copyright © 2020 Atomist, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.JavaProjectStructure = exports.KotlinPackage = void 0;
const antlr_1 = require("@atomist/antlr");
const astUtils_1 = require("@atomist/automation-client/lib/tree/ast/astUtils");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const _ = require("lodash");
const javaProjectUtils_1 = require("./javaProjectUtils");
const javaPathExpressions_1 = require("./query/javaPathExpressions");
/**
 * Path expression using the Kotlin grammar for a Java package declaration
 */
exports.KotlinPackage = "//packageHeader//identifier";
/**
 * Represents Java project structure (nested packages following Java naming conventions)
 * which can be inferred from project contents.
 * Also works for Kotlin.
 */
class JavaProjectStructure {
    /**
     * @param applicationPackage The first Java package found in the project.
     */
    constructor(applicationPackage) {
        this.applicationPackage = applicationPackage;
    }
    /**
     * Find root Java or Kotlin package
     * @param {ProjectAsync} p
     * @return {Promise<JavaProjectStructure>}
     */
    static async infer(p) {
        // Treat Java and Kotlin as one
        const packages = (await astUtils_1.gather(p, {
            parseWith: antlr_1.Java9FileParser,
            globPatterns: javaProjectUtils_1.JavaSourceFiles,
            pathExpression: javaPathExpressions_1.JavaPackage,
            // TODO workaround for recursive ANTLR bug
            mapper: m => m.$value.replace(/.*package (.*);/, "$1"),
        })).concat((await astUtils_1.matches(p, {
            parseWith: antlr_1.KotlinFileParser,
            globPatterns: javaProjectUtils_1.KotlinSourceFiles,
            pathExpression: exports.KotlinPackage,
        })).map(m => m.$value));
        const uniquePackages = _.uniq(packages);
        if (uniquePackages.length === 0) {
            return undefined;
        }
        if (uniquePackages.length === 1) {
            const jps = new JavaProjectStructure(uniquePackages[0]);
            logger_1.logger.debug("Successful JavaProjectStructure inference on %j: Sole package is %j", p.id, jps);
            return jps;
        }
        const longestPrefix = sharedStart(uniquePackages);
        if (!!longestPrefix) {
            const jps = new JavaProjectStructure(longestPrefix.replace(/\.$/, ""));
            logger_1.logger.debug("Successful JavaProjectStructure inference on %j: Shortest path is %j", p.id, jps);
            return jps;
        }
        else {
            logger_1.logger.debug("Unsuccessful JavaProjectStructure inference on %j", p.id);
            return undefined;
        }
    }
}
exports.JavaProjectStructure = JavaProjectStructure;
// Taken from https://stackoverflow.com/questions/1916218/find-the-longest-common-starting-substring-in-a-set-of-strings
function sharedStart(array) {
    const A = array.concat().sort();
    if (!A) {
        return "";
    }
    const a1 = A[0];
    const a2 = A[A.length - 1];
    const L = a1.length;
    let i = 0;
    while (i < L && a1.charAt(i) === a2.charAt(i)) {
        i++;
    }
    return a1.substring(0, i);
}
//# sourceMappingURL=JavaProjectStructure.js.map