//#region import
import { load } from 'tnp-core/lib-prod';
import { config } from 'tnp-core/lib-prod';
import { chalk, crossPlatformPath, path, ___NS__cloneDeep, ___NS__isEqual, ___NS__isString, ___NS__isUndefined, ___NS__kebabCase, Utils__NS__uniqArray, UtilsTerminal__NS__select } from 'tnp-core/lib-prod';
import { Helpers__NS__exists, Helpers__NS__info, Helpers__NS__readFile, Helpers__NS__readJson, Helpers__NS__warn, Helpers__NS__writeFile, Helpers__NS__writeJson } from 'tnp-core/lib-prod';
import { LinkedPorjectsConfig, LinkedProject, HelpersTaon__NS__git__NS__isValidRepoUrl, HelpersTaon__NS__git__NS__originHttpToSsh, HelpersTaon__NS__git__NS__originSshToHttp, UtilsTypescript__NS__formatFile } from '../../index';
import { BaseFeatureForProject } from './base-feature-for-project';
//#endregion
export class BaseLinkedProjects extends BaseFeatureForProject {
    cache = {};
    //#region methods & getters / embedded project
    get embeddedProject() {
        const cacheKey = 'embeddedProject' + ___NS__kebabCase(this.project.location);
        if (!___NS__isUndefined(this.cache[cacheKey])) {
            return this.cache[cacheKey];
        }
        // Helpers__NS__taskStarted(`Detecting embedded project for ${this.location}`); // TODO it is slow
        const nearsetProj = this.project.ins.nearestTo(crossPlatformPath([this.project.location, '..']));
        const linkedPorj = nearsetProj?.linkedProjects?.linkedProjects.find(l => {
            const copareTo = 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 = crossPlatformPath([
            nearsetProj.location,
            linkedPorj.relativeClonePath,
            linkedPorj.internalRealtiveProjectPath || '',
        ]);
        const embdedresult = this.project.ins.From(pathToEmbededProj);
        // Helpers__NS__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__NS__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__NS__info(`Location saved to db for ${this.genericName}, db: ${this.ins.projectsDbLocation(___NS__kebabCase(this.cliToolName))}`);
            }
            catch (error) {
                Helpers__NS__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 {
                Helpers__NS__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 = ___NS__isString(linkedProj)
            ? LinkedProject.fromName(linkedProj)
            : linkedProj;
        const linkedProjectsConfig = this.getLinkedProjectsConfig();
        const linkedProjectToAdd = LinkedProject.from(linkedProject);
        const newProjRemoteHttpUrl = HelpersTaon__NS__git__NS__originSshToHttp(linkedProjectToAdd.remoteUrl());
        const newProjRemoteSshUrl = HelpersTaon__NS__git__NS__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) {
            Helpers__NS__warn(`[${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 (!Helpers__NS__exists(this.linkedProjectsConfigPath)) {
            return;
        }
        const orgContent = Helpers__NS__readFile(this.linkedProjectsConfigPath);
        const tmpJson = Helpers__NS__readJson(this.linkedProjectsConfigTempPath);
        linkedPorjectsConfig = LinkedPorjectsConfig.from(linkedPorjectsConfig);
        if (!Helpers__NS__exists(this.linkedProjectsConfigTempPath)) {
            Helpers__NS__writeJson(this.linkedProjectsConfigTempPath, linkedPorjectsConfig);
        }
        const jsonsAreEqual = ___NS__isEqual(tmpJson, JSON.parse(JSON.stringify(linkedPorjectsConfig)));
        if (jsonsAreEqual) {
            // linked projects.json only save/formatted when changed
            return;
        }
        const writer = load(orgContent);
        writer.write(linkedPorjectsConfig);
        const newContent = writer.toSource({
            quote: 'double',
            trailingComma: true,
            quotaKey: true,
        });
        Helpers__NS__writeJson(this.linkedProjectsConfigTempPath, linkedPorjectsConfig);
        Helpers__NS__writeFile(this.linkedProjectsConfigPath, newContent);
        // TODO to many formatting request because of jsonc
        if (!options.skipFormat) {
            this.formatConfigFile();
        }
        //#endregion
    }
    //#endregion
    formatConfigFile() {
        //#region @backendFunc
        UtilsTypescript__NS__formatFile(this.linkedProjectsConfigPath);
        //#endregion
    }
    //#region methods & getters  / get linked projects config path
    get linkedProjectsConfigPath() {
        return this.project.pathFor(config.file.linked_projects_json);
    }
    get linkedProjectsConfigTempPath() {
        return this.project.pathFor([`tmp-${config.file.linked_projects_json}`]);
    }
    //#endregion
    //#region methods & getters  / recreate linked projects config
    recreateLinkedProjectsConfig() {
        //#region @backendFunc
        if (!Helpers__NS__exists(this.linkedProjectsConfigPath) &&
            Helpers__NS__exists(this.project.pathFor(config.file.taon_jsonc))) {
            Helpers__NS__writeJson(this.linkedProjectsConfigPath, LinkedPorjectsConfig.from({ projects: [] }));
        }
        //#endregion
    }
    //#endregion
    //#region methods & getters  / get linked projects config
    getLinkedProjectsConfig() {
        //#region @backendFunc
        this.recreateLinkedProjectsConfig();
        const existedConfig = Helpers__NS__readJson(this.project.pathFor(config.file.linked_projects_json), {}, true);
        const orgExistedConfig = ___NS__cloneDeep(existedConfig);
        // console.log({ existedConfig });
        let linkedPorjectsConfig = LinkedPorjectsConfig.from(existedConfig);
        const currentRemoteUrl = this.project.git.originURL || '';
        const currentBranch = this.project.git.currentBranchName;
        linkedPorjectsConfig.projects = (linkedPorjectsConfig.projects || []).map((projOrProjName) => {
            if (___NS__isString(projOrProjName)) {
                return LinkedProject.fromName(projOrProjName, currentRemoteUrl, currentBranch);
            }
            if (!projOrProjName.relativeClonePath) {
                projOrProjName.relativeClonePath = path
                    .basename(projOrProjName.remoteUrl())
                    .replace('.git', '');
            }
            projOrProjName = LinkedProject.from(projOrProjName);
            if (!projOrProjName.remoteUrl() &&
                currentRemoteUrl &&
                HelpersTaon__NS__git__NS__isValidRepoUrl(currentRemoteUrl)) {
                projOrProjName.repoUrl = currentRemoteUrl.replace(path.basename(currentRemoteUrl), `${projOrProjName.relativeClonePath}.git`);
            }
            return projOrProjName;
        });
        // console.log({ linkedPorjectsConfig })
        // @ts-ignore
        linkedPorjectsConfig.projects = Utils__NS__uniqArray(linkedPorjectsConfig.projects, 'relativeClonePath');
        if (!___NS__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 = 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) {
                Helpers__NS__info(`
    Missing linked projects detected..

          `);
                Helpers__NS__info(`

${projectsThatShouldBeLinked
                    .map((p, index) => `- ${index + 1}. ${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 UtilsTerminal__NS__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})
                        Helpers__NS__info(`Cloning unexisted project from url ` +
                            `${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') {
                    Helpers__NS__info(`Exiting process...`);
                    process.exit(0);
                }
            }
        }
        //#endregion
    }
}
//# sourceMappingURL=c:/Users/darek/projects/npm/taon-dev/tnp-helpers/dist-nocutsrc-prod/lib/base/classes/base-linked-projects.js.map