"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProjectHelper = void 0;
const path = require("path");
const _ = require("lodash");
const yok_1 = require("./yok");
const constants_1 = require("../constants");
class ProjectHelper {
    constructor($logger, $fs, $staticConfig, $errors, $options) {
        this.$logger = $logger;
        this.$fs = $fs;
        this.$staticConfig = $staticConfig;
        this.$errors = $errors;
        this.$options = $options;
        this.cachedProjectDir = "";
    }
    get projectDir() {
        if (this.cachedProjectDir !== "") {
            return this.cachedProjectDir;
        }
        this.cachedProjectDir = null;
        let projectDir = path.resolve(this.$options.path || ".");
        while (true) {
            this.$logger.trace("Looking for project in '%s'", projectDir);
            const projectFilePath = path.join(projectDir, this.$staticConfig.PROJECT_FILE_NAME);
            if (this.$fs.exists(projectFilePath) &&
                this.isProjectFileCorrect(projectFilePath)) {
                this.$logger.trace("Project directory is '%s'.", projectDir);
                this.cachedProjectDir = projectDir;
                break;
            }
            const dir = path.dirname(projectDir);
            if (dir === projectDir) {
                this.$logger.trace("No project found at or above '%s'.", this.$options.path || path.resolve("."));
                break;
            }
            projectDir = dir;
        }
        return this.cachedProjectDir;
    }
    generateDefaultAppId(appName, baseAppId) {
        let sanitizedName = this.sanitizeName(appName);
        if (sanitizedName) {
            if (/^\d+$/.test(sanitizedName)) {
                sanitizedName = "the" + sanitizedName;
            }
        }
        else {
            sanitizedName = "the";
        }
        return `${baseAppId}.${sanitizedName}`;
    }
    sanitizeName(appName) {
        const sanitizedName = _.filter(appName.split(""), (c) => /[a-zA-Z0-9]/.test(c)).join("");
        return sanitizedName;
    }
    isProjectFileCorrect(projectFilePath) {
        try {
            const fileContent = this.$fs.readText(projectFilePath);
            return (fileContent.includes(constants_1.SCOPED_TNS_CORE_MODULES) ||
                fileContent.includes(constants_1.TNS_CORE_MODULES_NAME));
        }
        catch (err) {
            this.$errors.fail("The project file is corrupted. Additional technical information: %s", err);
        }
        return false;
    }
}
exports.ProjectHelper = ProjectHelper;
yok_1.injector.register("projectHelper", ProjectHelper);
//# sourceMappingURL=project-helper.js.map