"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseLinkedProjects = void 0;
//#region import
const lib_1 = require("tnp-core/lib");
const lib_2 = require("tnp-core/lib");
const lib_3 = require("tnp-core/lib");
const lib_4 = require("tnp-core/lib");
const index_1 = require("../../index");
const base_feature_for_project_1 = require("./base-feature-for-project");
//#endregion
class BaseLinkedProjects extends base_feature_for_project_1.BaseFeatureForProject {
    cache = {};
    //#region methods & getters / embedded project
    get embeddedProject() {
        const cacheKey = 'embeddedProject' + lib_3._.kebabCase(this.project.location);
        if (!lib_3._.isUndefined(this.cache[cacheKey])) {
            return this.cache[cacheKey];
        }
        // Helpers.taskStarted(`Detecting embedded project for ${this.location}`); // TODO it is slow
        const nearsetProj = this.project.ins.nearestTo((0, lib_3.crossPlatformPath)([this.project.location, '..']));
        const linkedPorj = nearsetProj?.linkedProjects?.linkedProjects.find(l => {
            const copareTo = (0, lib_3.crossPlatformPath)([
                nearsetProj.location,
                l.relativeClonePath,
            ]);
            if (this.project.location === copareTo) {
                return true;
            }
            if (l.remoteUrl() === this.project.git.originURL) {
                return true;
            }
            return false;
        });
        if (!linkedPorj || !linkedPorj.internalRealtiveProjectPath) {
            return;
        }
        const pathToEmbededProj = (0, lib_3.crossPlatformPath)([
            nearsetProj.location,
            linkedPorj.relativeClonePath,
            linkedPorj.internalRealtiveProjectPath || '',
        ]);
        const embdedresult = this.project.ins.From(pathToEmbededProj);
        // Helpers.taskDone(`Embedded project detected for ${this.location}`);
        this.cache[cacheKey] = embdedresult;
        return this.cache[cacheKey];
    }
    //#endregion
    //#region methods & getters / projects db location
    get projectsDbLocation() {
        //#region @backendFunc
        return this.project.ins.projectsDb.projectsDbLocation;
        //#endregion
    }
    //#endregion
    //#region methods & getters / save location to db
    async saveLocationToDB() {
        //#region @backendFunc
        const db = await this.project.ins.projectsDb.getConnection();
        const existed = db.data.projects.find(f => f.location === this.project.location);
        // Helpers.info(`Saving location to db for ${this.genericName}, exised: ${!!existed}`);
        if (!existed) {
            try {
                await db.update(data => {
                    if (data.projects.length > 50) {
                        data.projects.shift();
                    }
                    data.projects.push({
                        location: this.project.location,
                    });
                });
                // Helpers.info(`Location saved to db for ${this.genericName}, db: ${this.ins.projectsDbLocation(_.kebabCase(this.cliToolName))}`);
            }
            catch (error) {
                lib_4.Helpers.warn(`Cannot save location to db`);
            }
        }
        //#endregion
    }
    //#endregion
    //#region methods & getters / save all linked projects to db
    async saveAllLinkedProjectsToDB() {
        const proj = this.project;
        await proj.linkedProjects.saveLocationToDB();
        for (const link of proj.linkedProjects.linkedProjects) {
            const linkedPorj = this.project.ins.From([
                proj.location,
                link.relativeClonePath,
                link.internalRealtiveProjectPath || '',
            ]);
            // console.log({ linkedPorj })
            if (linkedPorj) {
                await linkedPorj.linkedProjects.saveLocationToDB();
            }
            else {
                lib_4.Helpers.warn(`
          In project ${proj.genericName}

          Folder ${link.relativeClonePath} is missing projects...

          `);
            }
        }
    }
    //#endregion
    //#region methods & getters  / add linked project
    addLinkedProject(linkedProj, options) {
        //#region @backendFunc
        options = options || {};
        const linkedProject = lib_3._.isString(linkedProj)
            ? index_1.LinkedProject.fromName(linkedProj)
            : linkedProj;
        const linkedProjectsConfig = this.getLinkedProjectsConfig();
        const linkedProjectToAdd = index_1.LinkedProject.from(linkedProject);
        const newProjRemoteHttpUrl = index_1.HelpersTaon.git.originSshToHttp(linkedProjectToAdd.remoteUrl());
        const newProjRemoteSshUrl = index_1.HelpersTaon.git.originHttpToSsh(linkedProjectToAdd.remoteUrl());
        const httpExists = linkedProjectsConfig.projects.some(p => p.repoUrlHttp === newProjRemoteHttpUrl &&
            p.relativeClonePath === linkedProjectToAdd.relativeClonePath);
        const sshExists = linkedProjectsConfig.projects.some(p => p.repoUrlSsh === newProjRemoteSshUrl &&
            p.relativeClonePath === linkedProjectToAdd.relativeClonePath);
        if (httpExists || sshExists) {
            lib_4.Helpers.warn(`[${lib_2.config.frameworkName}-helpers][linked-projects] ` +
                `Project "${linkedProjectToAdd.remoteUrl()}" ` +
                `already exists in linked projects`);
            return;
        }
        linkedProjectsConfig.projects.push(linkedProjectToAdd);
        this.setLinkedProjectsConfig(linkedProjectsConfig, options);
        //#endregion
    }
    //#endregion
    //#region methods & getters  / add linked projects
    addLinkedProjects(linkedProjs, options) {
        //#region @backendFunc
        options = options || {};
        for (const linkedProj of linkedProjs) {
            this.addLinkedProject(linkedProj, options);
        }
        //#endregion
    }
    //#endregion
    //#region methods & getters  / set linked projects config
    setLinkedProjectsConfig(linkedPorjectsConfig, options) {
        //#region @backendFunc
        options = options || {};
        if (!lib_4.Helpers.exists(this.linkedProjectsConfigPath)) {
            return;
        }
        const orgContent = lib_4.Helpers.readFile(this.linkedProjectsConfigPath);
        const tmpJson = lib_4.Helpers.readJson(this.linkedProjectsConfigTempPath);
        linkedPorjectsConfig = index_1.LinkedPorjectsConfig.from(linkedPorjectsConfig);
        if (!lib_4.Helpers.exists(this.linkedProjectsConfigTempPath)) {
            lib_4.Helpers.writeJson(this.linkedProjectsConfigTempPath, linkedPorjectsConfig);
        }
        const jsonsAreEqual = lib_3._.isEqual(tmpJson, JSON.parse(JSON.stringify(linkedPorjectsConfig)));
        if (jsonsAreEqual) {
            // linked projects.json only save/formatted when changed
            return;
        }
        const writer = (0, lib_1.load)(orgContent);
        writer.write(linkedPorjectsConfig);
        const newContent = writer.toSource({
            quote: 'double',
            trailingComma: true,
            quotaKey: true,
        });
        lib_4.Helpers.writeJson(this.linkedProjectsConfigTempPath, linkedPorjectsConfig);
        lib_4.Helpers.writeFile(this.linkedProjectsConfigPath, newContent);
        // TODO to many formatting request because of jsonc
        if (!options.skipFormat) {
            this.formatConfigFile();
        }
        //#endregion
    }
    //#endregion
    formatConfigFile() {
        //#region @backendFunc
        index_1.UtilsTypescript.formatFile(this.linkedProjectsConfigPath);
        //#endregion
    }
    //#region methods & getters  / get linked projects config path
    get linkedProjectsConfigPath() {
        return this.project.pathFor(lib_2.config.file.linked_projects_json);
    }
    get linkedProjectsConfigTempPath() {
        return this.project.pathFor([`tmp-${lib_2.config.file.linked_projects_json}`]);
    }
    //#endregion
    //#region methods & getters  / recreate linked projects config
    recreateLinkedProjectsConfig() {
        //#region @backendFunc
        if (!lib_4.Helpers.exists(this.linkedProjectsConfigPath) &&
            lib_4.Helpers.exists(this.project.pathFor(lib_2.config.file.taon_jsonc))) {
            lib_4.Helpers.writeJson(this.linkedProjectsConfigPath, index_1.LinkedPorjectsConfig.from({ projects: [] }));
        }
        //#endregion
    }
    //#endregion
    //#region methods & getters  / get linked projects config
    getLinkedProjectsConfig() {
        //#region @backendFunc
        this.recreateLinkedProjectsConfig();
        const existedConfig = lib_4.Helpers.readJson(this.project.pathFor(lib_2.config.file.linked_projects_json), {}, true);
        const orgExistedConfig = lib_3._.cloneDeep(existedConfig);
        // console.log({ existedConfig });
        let linkedPorjectsConfig = index_1.LinkedPorjectsConfig.from(existedConfig);
        const currentRemoteUrl = this.project.git.originURL || '';
        const currentBranch = this.project.git.currentBranchName;
        linkedPorjectsConfig.projects = (linkedPorjectsConfig.projects || []).map((projOrProjName) => {
            if (lib_3._.isString(projOrProjName)) {
                return index_1.LinkedProject.fromName(projOrProjName, currentRemoteUrl, currentBranch);
            }
            if (!projOrProjName.relativeClonePath) {
                projOrProjName.relativeClonePath = lib_3.path
                    .basename(projOrProjName.remoteUrl())
                    .replace('.git', '');
            }
            projOrProjName = index_1.LinkedProject.from(projOrProjName);
            if (!projOrProjName.remoteUrl() &&
                currentRemoteUrl &&
                index_1.HelpersTaon.git.isValidRepoUrl(currentRemoteUrl)) {
                projOrProjName.repoUrl = currentRemoteUrl.replace(lib_3.path.basename(currentRemoteUrl), `${projOrProjName.relativeClonePath}.git`);
            }
            return projOrProjName;
        });
        // console.log({ linkedPorjectsConfig })
        // @ts-ignore
        linkedPorjectsConfig.projects = lib_3.Utils.uniqArray(linkedPorjectsConfig.projects, 'relativeClonePath');
        if (!lib_3._.isEqual(orgExistedConfig, linkedPorjectsConfig)) {
            this.setLinkedProjectsConfig(linkedPorjectsConfig);
        }
        return linkedPorjectsConfig;
        //#endregion
    }
    //#endregion
    //#region methods & getters  / linked projects
    get linkedProjects() {
        return this.getLinkedProjectsConfig().projects || [];
    }
    //#endregion
    //#region methods & getters  / detected linked projects
    get detectedLinkedProjects() {
        const detectedLinkedProjects = index_1.LinkedProject.detect(this.project.location, { recursive: true });
        return detectedLinkedProjects;
    }
    //#endregion
    //#region methods & getters  / linked projects prefix
    get linkedProjectsPrefix() {
        return this.getLinkedProjectsConfig().prefix;
    }
    //#endregion
    //#region getters & methods / reset linked projects only to core branches
    resetLinkedProjectsOnlyToCoreBranches() {
        return false;
    }
    //#endregion
    //#region getters & methods / get unexisted projects
    async cloneNonexistedLinkedProjects(setOrigin) {
        //#region @backendFunc
        const detectedLinkedProjects = this.detectedLinkedProjects;
        if (!this.project.isMonorepo) {
            const projectsThatShouldBeLinked = this.linkedProjects
                .map(linkedProj => {
                return detectedLinkedProjects.find(f => f.relativeClonePath === linkedProj.relativeClonePath)
                    ? void 0
                    : linkedProj;
            })
                .filter(f => !!f);
            if (projectsThatShouldBeLinked.length > 0) {
                lib_4.Helpers.info(`
    Missing linked projects detected..

          `);
                lib_4.Helpers.info(`

${projectsThatShouldBeLinked
                    .map((p, index) => `- ${index + 1}. ${lib_3.chalk.bold(p.relativeClonePath)} ` +
                    `${p.remoteUrlTransformed(setOrigin)} ` +
                    `${p.purpose ? `{ purpose: ${p.purpose} }` : ''}`)
                    .join('\n')}

        `);
                if (projectsThatShouldBeLinked.length === 0) {
                    return;
                }
                const optionsClone = {
                    cloneAndContinue: {
                        name: 'Clone missing projects and continue',
                    },
                    cloneAndExit: {
                        name: 'Clone missing projects and exit process',
                    },
                    exit: {
                        name: 'Exit process',
                    },
                };
                const res = await lib_3.UtilsTerminal.select({
                    choices: optionsClone,
                    question: `What do you want to do with missing linked projects ?`,
                });
                if (res === 'cloneAndContinue' || res === 'cloneAndExit') {
                    for (const linkedProj of projectsThatShouldBeLinked) {
                        // console.log({linkedProj})
                        lib_4.Helpers.info(`Cloning unexisted project from url ` +
                            `${lib_3.chalk.bold(linkedProj.remoteUrlTransformed(setOrigin))} ` +
                            `to ${linkedProj.relativeClonePath}`);
                        await this.project.git.clone(linkedProj.remoteUrlTransformed(setOrigin), linkedProj.relativeClonePath, linkedProj.defaultBranch);
                        const childProjLocaiton = this.project.pathFor([
                            linkedProj.relativeClonePath,
                            linkedProj.internalRealtiveProjectPath,
                        ]);
                        const childProj = this.project.ins.From(childProjLocaiton);
                        if (childProj) {
                            await childProj.linkedProjects.saveLocationToDB();
                        }
                    }
                }
                if (res === 'cloneAndExit' || res === 'exit') {
                    lib_4.Helpers.info(`Exiting process...`);
                    process.exit(0);
                }
            }
        }
        //#endregion
    }
}
exports.BaseLinkedProjects = BaseLinkedProjects;
//# sourceMappingURL=base-linked-projects.js.map