"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatNumbers = exports.numberWithCommas = exports.roundToXDigits = exports.round = exports.uniqueDates = exports.getDigitsFrequencies = exports.convertToPercentage = void 0;
const Inventory_model_1 = require("../models/Inventory.model");
const Receivable_model_1 = require("../models/Receivable.model");
const collaterals_enum_1 = require("../enums/collaterals.enum");
const defaultFormatterOptions = {
    fractions: 2,
};
const convertToPercentage = (value, total) => {
    return ((100 * value) / total).toFixed(2);
};
exports.convertToPercentage = convertToPercentage;
const getDigitsFrequencies = (firstDigits) => {
    const digitCounts = Array(10).fill(0);
    for (const n of firstDigits) {
        digitCounts[n]++;
    }
    return digitCounts;
};
exports.getDigitsFrequencies = getDigitsFrequencies;
const uniqueDates = async (borrowerId, deep, collateral) => {
    let bbcDates;
    switch (collateral) {
        case collaterals_enum_1.ECollaterals.INVENTORY:
            bbcDates = await Inventory_model_1.InventoryModel.find({ borrowerId }, { _id: 1, bbcDate: 1 }).sort([['bbcDate', -1]]);
            break;
        case collaterals_enum_1.ECollaterals.RECEIVABLE:
            bbcDates = await Receivable_model_1.ReceivableModel.find({ borrowerId }, { _id: 1, bbcDate: 1 }).sort([['bbcDate', -1]]);
            break;
        default:
            throw new Error('Wrong collateral type');
    }
    return [...new Set(bbcDates.map((i) => i.bbcDate.toString()))]
        .map((bbcDate) => ({ bbcDate: new Date(bbcDate) }))
        .sort((a, b) => new Date(a.bbcDate).valueOf() - new Date(b.bbcDate).valueOf())
        .slice(-deep);
};
exports.uniqueDates = uniqueDates;
const round = (num) => {
    const m = Number((Math.abs(num) * 100).toPrecision(15));
    return Math.round(m) / 100 * Math.sign(num);
};
exports.round = round;
const roundToXDigits = (value, digits = 2) => {
    value = value * Math.pow(10, digits);
    value = Math.round(value);
    value = value / Math.pow(10, digits);
    return value;
};
exports.roundToXDigits = roundToXDigits;
function numberWithCommas(x) {
    try {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
    catch (e) {
        return x.toString();
    }
}
exports.numberWithCommas = numberWithCommas;
function formatNumbers(value, formatterOptions) {
    try {
        const options = { ...defaultFormatterOptions, ...formatterOptions };
        if (typeof value !== 'number') {
            return value;
        }
        value = Number(value);
        if (value === 0 && options.nullValue) {
            return options.nullValue;
        }
        return numberWithCommas((Math.round(Number(value) * 100) / 100).toFixed(options.fractions));
    }
    catch (e) {
        return value.toString();
    }
}
exports.formatNumbers = formatNumbers;
