import { formatCurrency } from "@angular/common";

export class NumberUtils {

    public static Ordinal(value: number): string {
        let suffix = '';
        const last = value % 10;
        const specialLast = value % 100;
        if (!value || value < 1) {
            return value.toString();
        }
        if (last === 1 && specialLast !== 11) {
            suffix = 'st';
        } else if (last === 2 && specialLast !== 12) {
            suffix = 'nd';
        } else if (last === 3 && specialLast !== 13) {
            suffix = 'rd';
        } else {
            suffix = 'th';
        }
        return value + suffix;
    }

    public static Clamp(n: number, min: number, max: number): number {
        return Math.min(max, Math.max(min, n));
    }

    public static SortFunction(a: number, b: number): number {
        return a - b;
    }

    public static Sum(array: number[], key: any = undefined): number {
        if (key) {
            return array.reduce((a, b) => (isNaN(a[key]) ? 0 : a[key]) + (isNaN(b[key]) ? 0 : b[key]), 0);
        }
        return array.reduce((a, b) => (isNaN(a) ? 0 : a) + (isNaN(b) ? 0 : b), 0);
    }

    public static FormatCurrency(v: number, zeroExpression: string = '0'): string {

        return ['', 0, null, undefined, NaN].includes(v) ? zeroExpression : formatCurrency(v, "en", "", "", `0.2`);
    }
    public static Round(num, precision) {
        const factor = 10 ** precision;
        return Math.round(num * factor) / factor;
    }

    public static RoundCurrency(num) {
        return this.Round(num, 2);
    }

    public static VersionDiff(v1: string, v2: string) {
        let versionDefine = [
            { index: 0, name: 'major' },
            { index: 1, name: 'minor' },
            { index: 2, name: 'patch' },
            { index: 3, name: 'build' }
        ]
        if (v1 && v2) {
            let v1Versions = v1.split('.');
            let v2Versions = v2.split('.');

            for (let i = 0; i < v1Versions.length; i++) {
                if (v2Versions.length == i) return versionDefine[i];
                if (v1Versions[i] != v2Versions[i]) return versionDefine[i];
            }
        }
        return null;
    }
}
