import {isNil} from "lodash";

export const getDigitsCount = (num: number): number => {
    if (num === 0) return 1;
    return Math.floor(Math.log10(Math.abs(num))) + 1;
};
export const getPluralForm = (amount: number, one: string, twoFour: string, many: string): string => {
    if (amount % 100 >= 11 && amount % 100 <= 14) {
        return many;
    }
    switch (amount % 10) {
        case 1:
            return one;
        case 2:
        case 3:
        case 4:
            return twoFour;
        default:
            return many;
    }
};

type KeysOf<T> = (keyof T)[];

// Универсальная функция для получения ключей интерфейса
export function getKeys<T extends object>(): KeysOf<T> {
    return Object.keys({} as T) as KeysOf<T>;
}


export const IMAGE_MIME_TYPES = [
    "image/png",
    "image/jpeg",
    "image/gif",
    "image/bmp",
    "image/tiff",
    "image/x-icon",
    "image/webp",
    "image/svg+xml",
    "image/heic"
];

export const isNilOrEmptyString = (value: unknown): value is null | undefined | '' => {
    return isNil(value) || (typeof value === 'string' && value.trim() === '');
}

export function base64ToBlob(base64: string, type: string) {
    const binaryString = window.atob(base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; ++i) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return new Blob([bytes], {type: type});
}

export function writeToFile(data: string, filename: string, type: string) {
    const blobValue = base64ToBlob(data, type);
    const blobURL = URL.createObjectURL(blobValue);
    const blobLink = document.createElement('a');
    blobLink.setAttribute('download', filename);
    blobLink.href = blobURL;
    document.body.appendChild(blobLink);
    blobLink.click();
    document.body.removeChild(blobLink);
}
