"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFeatureTableMd = exports.getFeatureEnabled = exports.getFeatureLabel = exports.getFeaturesByPlan = exports.getFeatureById = exports.getAllFeatureIds = exports.getFeatureLabelsByPlan = exports.getFeatureIdsByPlan = exports.PriceCurrency = exports.PricePeriod = exports.PlanName = void 0;
exports.loadStripeConfig = loadStripeConfig;
exports.findPrice = findPrice;
exports.getPlans = getPlans;
const fs = require("fs-extra");
const markdownUtils_1 = require("../../markdownUtils");
const locale_1 = require("../../locale");
const html_1 = require("@joplin/utils/html");
var PlanName;
(function (PlanName) {
    PlanName["Basic"] = "basic";
    PlanName["Pro"] = "pro";
    PlanName["Teams"] = "teams";
    PlanName["JoplinServerBusiness"] = "joplinServerBusiness";
})(PlanName || (exports.PlanName = PlanName = {}));
var PlanHostingType;
(function (PlanHostingType) {
    PlanHostingType["Managed"] = "managed";
    PlanHostingType["Self"] = "self";
})(PlanHostingType || (PlanHostingType = {}));
var PricePeriod;
(function (PricePeriod) {
    PricePeriod["Monthly"] = "monthly";
    PricePeriod["Yearly"] = "yearly";
})(PricePeriod || (exports.PricePeriod = PricePeriod = {}));
var PriceCurrency;
(function (PriceCurrency) {
    PriceCurrency["EUR"] = "EUR";
    PriceCurrency["GBP"] = "GBP";
    PriceCurrency["USD"] = "USD";
})(PriceCurrency || (exports.PriceCurrency = PriceCurrency = {}));
function formatPrice(amount, currency) {
    amount = typeof amount === 'number' ? (Math.ceil(amount * 100) / 100).toFixed(2) : amount;
    if (currency === PriceCurrency.EUR)
        return `${amount}€`;
    if (currency === PriceCurrency.GBP)
        return `£${amount}`;
    if (currency === PriceCurrency.USD)
        return `$${amount}`;
    throw new Error(`Unsupported currency: ${currency}`);
}
function loadStripeConfig(env, filePath) {
    const config = JSON.parse(fs.readFileSync(filePath, 'utf8'))[env];
    if (!config)
        throw new Error(`Invalid env: ${env}`);
    const decoratePrices = (p) => {
        return Object.assign(Object.assign({}, p), { formattedAmount: formatPrice(p.amount, p.currency), formattedMonthlyAmount: p.period === PricePeriod.Monthly ? formatPrice(p.amount, p.currency) : formatPrice(Number(p.amount) / 12, p.currency) });
    };
    config.prices = config.prices.map(decoratePrices);
    config.archivedPrices = config.archivedPrices.map(decoratePrices);
    return config;
}
function findPrice(config, query) {
    let output = null;
    for (const prices of [config.prices, config.archivedPrices]) {
        if (query.accountType && query.period) {
            output = prices.filter(p => p.accountType === query.accountType).find(p => p.period === query.period);
        }
        else if (query.priceId) {
            output = prices.find(p => p.id === query.priceId);
        }
        else {
            throw new Error(`Invalid query: ${JSON.stringify(query)}`);
        }
        if (output)
            break;
    }
    if (!output)
        throw new Error(`Not found: ${JSON.stringify(query)}`);
    return output;
}
const features = () => {
    const shareNotebookTitle = (0, locale_1._)('Share a notebook with others');
    return {
        maxItemSize: {
            title: (0, locale_1._)('Max note or attachment size'),
            basic: true,
            pro: true,
            teams: true,
            basicInfo: (0, locale_1._)('%d MB per note or attachment', 10),
            proInfo: (0, locale_1._)('%d MB per note or attachment', 200),
            teamsInfo: (0, locale_1._)('%d MB per note or attachment', 200),
            basicInfoShort: (0, locale_1._)('%d MB', 10),
            proInfoShort: (0, locale_1._)('%d MB', 200),
            teamsInfoShort: (0, locale_1._)('%d MB', 200),
        },
        maxStorage: {
            title: (0, locale_1._)('Storage space'),
            basic: true,
            pro: true,
            teams: true,
            basicInfo: (0, locale_1._)('%d GB storage space', 2),
            proInfo: (0, locale_1._)('%d GB storage space', 30),
            teamsInfo: (0, locale_1._)('%d GB storage space', 50),
            basicInfoShort: (0, locale_1._)('%d GB', 2),
            proInfoShort: (0, locale_1._)('%d GB', 30),
            teamsInfoShort: (0, locale_1._)('%d GB', 50),
        },
        publishNote: {
            title: (0, locale_1._)('Publish notes to the internet'),
            description: 'You can [publish a note](https://joplinapp.org/help/apps/publish_note) from the Joplin app. You will get a link that you can share with other users, who can then view the note in their browser.',
            basic: true,
            pro: true,
            teams: true,
            joplinServerBusiness: true,
        },
        sync: {
            title: (0, locale_1._)('Sync as many devices as you want'),
            basic: true,
            pro: true,
            teams: true,
            joplinServerBusiness: true,
        },
        // clipper: {
        // 	title: _('Web Clipper'),
        // 	description: _('The [Web Clipper](%s) is a browser extension that allows you to save web pages and screenshots from your browser.', 'https://joplinapp.org/help/apps/clipper'),
        // 	basic: false,
        // 	pro: false,
        // 	teams: false,
        // },
        collaborate: {
            title: (0, locale_1._)('Collaborate on a notebook with others'),
            description: (0, locale_1._)('This allows another user to share a notebook with you, and you can then both collaborate on it. It does not however allow you to share a notebook with someone else, unless you have the feature "%s".', shareNotebookTitle),
            basic: true,
            pro: true,
            teams: true,
            joplinServerBusiness: true,
        },
        share: {
            title: shareNotebookTitle,
            description: 'You can [share a notebook](https://joplinapp.org/help/apps/share_notebook/) with other Joplin Cloud users, who can then view the notes and edit them.',
            basic: false,
            pro: true,
            teams: true,
            joplinServerBusiness: true,
        },
        emailToNote: {
            title: (0, locale_1._)('Email to Note'),
            description: '[Email to Note](https://joplinapp.org/help/apps/email_to_note/) allows you to save your emails in Joplin Cloud by forwarding your emails to a special email address. The subject of the email will become the note title, and the email body will become the note content.',
            basic: false,
            pro: true,
            teams: true,
            joplinServerBusiness: true,
        },
        customBanner: {
            title: (0, locale_1._)('Customise the note publishing banner'),
            description: 'You can [customise the banner](https://joplinapp.org/help/apps/publish_note#customising-the-publishing-banner) that appears on top of your published notes, for example by adding a custom logo and text, and changing the banner colour.',
            basic: false,
            pro: true,
            teams: true,
            joplinServerBusiness: true,
        },
        multiUsers: {
            title: (0, locale_1._)('Manage multiple users'),
            description: 'The [Teams functionality](https://joplinapp.org/help/apps/teams/) enables the efficient administration of multiple users within a team. Serving as a centralized hub, it provides an overview of all users within your organisations, facilitating easy addition or removal of members, as well as centralised billing.',
            basic: false,
            pro: false,
            teams: true,
            joplinServerBusiness: true,
        },
        consolidatedBilling: {
            title: (0, locale_1._)('Consolidated billing'),
            description: 'Billing is consolidated, ensuring a single monthly or yearly invoice, based on your chosen plan. The billing is automatically adjusted in accordance with the number of team members',
            basic: false,
            pro: false,
            teams: true,
        },
        sharePermissions: {
            title: (0, locale_1._)('Share permissions'),
            description: '[Share permissions](https://joplinapp.org/help/apps/share_permissions/) allow you to define whether a notebook you share with someone can be edited or is read-only. It can be useful for example to share documentation that you do not want to be modified.',
            basic: false,
            pro: false,
            teams: true,
            joplinServerBusiness: true,
        },
        prioritySupport: {
            title: (0, locale_1._)('Priority support'),
            basic: false,
            pro: false,
            teams: true,
            joplinServerBusiness: true,
        },
        selfHosted: {
            title: (0, locale_1._)('Self-hosted'),
            basic: false,
            pro: false,
            teams: false,
            joplinServerBusiness: true,
        },
        sourceCodeAvailable: {
            title: (0, locale_1._)('Source code available'),
            basic: false,
            pro: false,
            teams: false,
            joplinServerBusiness: true,
        },
    };
};
const getFeatureIdsByPlan = (planName, featureOn) => {
    const output = [];
    for (const [k, v] of Object.entries(features())) {
        if (v[planName] === featureOn) {
            output.push(k);
        }
    }
    return output;
};
exports.getFeatureIdsByPlan = getFeatureIdsByPlan;
const getFeatureLabelsByPlan = (planName, featureOn) => {
    const output = [];
    for (const [featureId, v] of Object.entries(features())) {
        if (v[planName] === featureOn) {
            output.push((0, exports.getFeatureLabel)(planName, featureId));
        }
    }
    return output;
};
exports.getFeatureLabelsByPlan = getFeatureLabelsByPlan;
const getAllFeatureIds = () => {
    return Object.keys(features());
};
exports.getAllFeatureIds = getAllFeatureIds;
const getFeatureById = (featureId) => {
    return features()[featureId];
};
exports.getFeatureById = getFeatureById;
const getFeaturesByPlan = (planName, featureOn) => {
    const output = [];
    for (const [, v] of Object.entries(features())) {
        if (v[planName] === featureOn) {
            output.push(v);
        }
    }
    return output;
};
exports.getFeaturesByPlan = getFeaturesByPlan;
const getFeatureLabel = (planName, featureId) => {
    const feature = features()[featureId];
    const k = `${planName}Info`;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
    if (feature[k])
        return feature[k];
    return feature.title;
};
exports.getFeatureLabel = getFeatureLabel;
const getFeatureEnabled = (planName, featureId) => {
    const feature = features()[featureId];
    return feature[planName];
};
exports.getFeatureEnabled = getFeatureEnabled;
const createFeatureTableMd = () => {
    const headers = [
        {
            name: 'featureLabel',
            label: 'Feature',
            disableHtmlEscape: true,
        },
        {
            name: 'basic',
            label: 'Basic',
        },
        {
            name: 'pro',
            label: 'Pro',
        },
        {
            name: 'teams',
            label: 'Teams',
        },
        {
            name: 'joplinServerBusiness',
            label: 'Joplin Server Business',
            labelUrl: 'https://joplinapp.org/help/apps/joplin_server_business',
        },
    ];
    const rows = [];
    const getCellInfo = (planName, feature) => {
        if (!feature[planName])
            return '-';
        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
        const infoShort = feature[`${planName}InfoShort`];
        if (infoShort)
            return infoShort;
        return '✔️';
    };
    const makeFeatureLabel = (featureId, feature) => {
        const output = [
            `${(0, html_1.htmlentities)(feature.title)}`,
        ];
        if (feature.description) {
            output.push(`<a data-id=${(0, html_1.htmlentities)(featureId)} class="feature-title" name="feature-${(0, html_1.htmlentities)(featureId)}" href="#feature-${(0, html_1.htmlentities)(featureId)}">i</a>`);
            output.push(`<div class="feature-description feature-description-${(0, html_1.htmlentities)(featureId)}">${(0, html_1.htmlentities)(feature.description)}</div>`);
        }
        return output.join('');
    };
    for (const [id, feature] of Object.entries(features())) {
        const row = {
            featureLabel: makeFeatureLabel(id, feature),
            basic: getCellInfo(PlanName.Basic, feature),
            pro: getCellInfo(PlanName.Pro, feature),
            teams: getCellInfo(PlanName.Teams, feature),
            joplinServerBusiness: getCellInfo(PlanName.JoplinServerBusiness, feature),
        };
        rows.push(row);
    }
    return markdownUtils_1.default.createMarkdownTable(headers, rows);
};
exports.createFeatureTableMd = createFeatureTableMd;
function getPlans(stripeConfig) {
    return {
        basic: {
            name: 'basic',
            title: (0, locale_1._)('Basic'),
            priceMonthly: findPrice(stripeConfig, {
                accountType: 1,
                period: PricePeriod.Monthly,
            }),
            priceYearly: findPrice(stripeConfig, {
                accountType: 1,
                period: PricePeriod.Yearly,
            }),
            featured: false,
            iconName: 'basic-icon',
            featuresOn: (0, exports.getFeatureIdsByPlan)(PlanName.Basic, true),
            featuresOff: (0, exports.getFeatureIdsByPlan)(PlanName.Basic, false),
            featureLabelsOn: (0, exports.getFeatureLabelsByPlan)(PlanName.Basic, true),
            featureLabelsOff: (0, exports.getFeatureLabelsByPlan)(PlanName.Basic, false),
            cfaLabel: (0, locale_1._)('Try it now'),
            cfaUrl: '',
            footnote: '',
            hostingType: PlanHostingType.Managed,
        },
        pro: {
            name: 'pro',
            title: (0, locale_1._)('Pro'),
            priceMonthly: findPrice(stripeConfig, {
                accountType: 2,
                period: PricePeriod.Monthly,
            }),
            priceYearly: findPrice(stripeConfig, {
                accountType: 2,
                period: PricePeriod.Yearly,
            }),
            featured: true,
            iconName: 'pro-icon',
            featuresOn: (0, exports.getFeatureIdsByPlan)(PlanName.Pro, true),
            featuresOff: (0, exports.getFeatureIdsByPlan)(PlanName.Pro, false),
            featureLabelsOn: (0, exports.getFeatureLabelsByPlan)(PlanName.Pro, true),
            featureLabelsOff: (0, exports.getFeatureLabelsByPlan)(PlanName.Pro, false),
            cfaLabel: (0, locale_1._)('Try it now'),
            cfaUrl: '',
            footnote: '',
            hostingType: PlanHostingType.Managed,
        },
        teams: {
            name: 'teams',
            title: (0, locale_1._)('Teams'),
            priceMonthly: findPrice(stripeConfig, {
                accountType: 3,
                period: PricePeriod.Monthly,
            }),
            priceYearly: findPrice(stripeConfig, {
                accountType: 3,
                period: PricePeriod.Yearly,
            }),
            featured: false,
            iconName: 'business-icon',
            featuresOn: (0, exports.getFeatureIdsByPlan)(PlanName.Teams, true),
            featuresOff: (0, exports.getFeatureIdsByPlan)(PlanName.Teams, false),
            featureLabelsOn: (0, exports.getFeatureLabelsByPlan)(PlanName.Teams, true),
            featureLabelsOff: (0, exports.getFeatureLabelsByPlan)(PlanName.Teams, false),
            cfaLabel: (0, locale_1._)('Try it now'),
            cfaUrl: '',
            footnote: (0, locale_1._)('Per user. Minimum of 2 users.'),
            hostingType: PlanHostingType.Managed,
        },
        joplinServerBusiness: {
            name: 'joplinServerBusiness',
            title: (0, locale_1._)('Joplin Server Business'),
            featured: false,
            iconName: 'business-icon',
            featuresOn: (0, exports.getFeatureIdsByPlan)(PlanName.JoplinServerBusiness, true),
            featuresOff: (0, exports.getFeatureIdsByPlan)(PlanName.JoplinServerBusiness, false),
            featureLabelsOn: (0, exports.getFeatureLabelsByPlan)(PlanName.JoplinServerBusiness, true),
            featureLabelsOff: (0, exports.getFeatureLabelsByPlan)(PlanName.JoplinServerBusiness, false),
            cfaLabel: (0, locale_1._)('Get a quote'),
            cfaUrl: 'https://tally.so/r/D4BlOE',
            footnote: '',
            learnMoreUrl: 'https://joplinapp.org/help/apps/joplin_server_business',
            hostingType: PlanHostingType.Self,
        },
    };
}
//# sourceMappingURL=index.js.map