"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.profileIdByIndex = exports.deleteProfileById = exports.createNewProfile = exports.isSubProfile = exports.getProfileFullPath = exports.getCurrentProfile = exports.saveProfileConfig = exports.loadProfileConfig = exports.migrateProfileConfig = void 0;
const path_utils_1 = require("../../path-utils");
const shim_1 = require("../../shim");
const types_1 = require("./types");
const non_secure_1 = require("nanoid/non-secure");
const locale_1 = require("../../locale");
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const migrateProfileConfig = (profileConfig, toVersion) => {
    let version = 2;
    while (profileConfig.version < toVersion) {
        if (profileConfig.version === 1) {
            for (const profile of profileConfig.profiles) {
                if (profile.path === '.') {
                    profile.id = types_1.DefaultProfileId;
                }
                else {
                    profile.id = profile.path.split('-').pop();
                }
                delete profile.path;
            }
            const currentProfile = profileConfig.profiles[profileConfig.currentProfile];
            profileConfig.currentProfileId = currentProfile.id;
            delete profileConfig.currentProfile;
        }
        profileConfig.version = version;
        version++;
    }
    return profileConfig;
};
exports.migrateProfileConfig = migrateProfileConfig;
const loadProfileConfig = async (profileConfigPath) => {
    if (!(await shim_1.default.fsDriver().exists(profileConfigPath))) {
        return (0, types_1.defaultProfileConfig)();
    }
    try {
        const configContent = await shim_1.default.fsDriver().readFile(profileConfigPath, 'utf8');
        let parsed = JSON.parse(configContent);
        if (!parsed.profiles || !parsed.profiles.length)
            throw new Error(`Profile config should contain at least one profile: ${profileConfigPath}`);
        parsed = (0, exports.migrateProfileConfig)(parsed, types_1.CurrentProfileVersion);
        const output = Object.assign(Object.assign({}, (0, types_1.defaultProfileConfig)()), parsed);
        for (let i = 0; i < output.profiles.length; i++) {
            output.profiles[i] = Object.assign(Object.assign({}, (0, types_1.defaultProfile)()), output.profiles[i]);
        }
        if (!output.profiles.find(p => p.id === output.currentProfileId))
            throw new Error(`Current profile ID is invalid: ${output.currentProfileId}`);
        return output;
    }
    catch (error) {
        error.message = `Could not parse profile configuration: ${profileConfigPath}: ${error.message}`;
        throw error;
    }
};
exports.loadProfileConfig = loadProfileConfig;
const saveProfileConfig = async (profileConfigPath, config) => {
    await shim_1.default.fsDriver().writeFile(profileConfigPath, JSON.stringify(config, null, '\t'), 'utf8');
};
exports.saveProfileConfig = saveProfileConfig;
const getCurrentProfile = (config) => {
    return config.profiles.find(p => p.id === config.currentProfileId);
};
exports.getCurrentProfile = getCurrentProfile;
const getProfileFullPath = (profile, rootProfilePath) => {
    const folderName = profile.id === types_1.DefaultProfileId ? '' : `/profile-${profile.id}`;
    return `${(0, path_utils_1.rtrimSlashes)(rootProfilePath)}${folderName}`;
};
exports.getProfileFullPath = getProfileFullPath;
const isSubProfile = (profile) => {
    return profile.id !== types_1.DefaultProfileId;
};
exports.isSubProfile = isSubProfile;
const profileIdGenerator = (0, non_secure_1.customAlphabet)('0123456789abcdefghijklmnopqrstuvwxyz', 8);
const createNewProfile = (config, profileName) => {
    const newConfig = Object.assign(Object.assign({}, config), { profiles: config.profiles.slice() });
    const newProfile = {
        name: profileName,
        id: profileIdGenerator(),
    };
    newConfig.profiles.push(newProfile);
    return {
        newConfig: newConfig,
        newProfile: newProfile,
    };
};
exports.createNewProfile = createNewProfile;
const deleteProfileById = (config, profileId) => {
    if (profileId === types_1.DefaultProfileId)
        throw new Error((0, locale_1._)('The default profile cannot be deleted'));
    if (profileId === config.currentProfileId)
        throw new Error((0, locale_1._)('The active profile cannot be deleted. Switch to a different profile and try again.'));
    const newProfiles = config.profiles.filter(p => p.id !== profileId);
    return Object.assign(Object.assign({}, config), { profiles: newProfiles });
};
exports.deleteProfileById = deleteProfileById;
const profileIdByIndex = (config, index) => {
    return config.profiles[index].id;
};
exports.profileIdByIndex = profileIdByIndex;
//# sourceMappingURL=index.js.map