// These are all file related functions.

// Use a defined list of unacceptable characters to remove from a filename.
// Updated 2024-10-18
export const clean_filename = function clean_filename(
    filename: any | string,
    unacceptable_chars: RegExp = /[ <>:"/\\|?*]/g,
    replacement_char: string = '_'
) {
    // console.log('*** clean_filename() ***');
    if (!filename) {
        return '';
    }

    const cleaned_filename = filename.replace(
        unacceptable_chars,
        replacement_char
    );
    // console.log(cleaned_filename);
    return cleaned_filename;
};

export const format_bytes = function format_bytes(
    bytes: number,
    decimals: number = 2
) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};

// Updated 2024-08-12
export const guess_file_name = function guess_file_name(
    filename_string: string
) {
    // console.log('*** guess_file_name() ***');
    if (!filename_string) {
        return '';
    }

    if (filename_string.includes('.')) {
        const file_name = filename_string.substring(
            0,
            filename_string.lastIndexOf('.')
        );
        // console.log(file_name);
        return file_name;
    } else {
        return filename_string;
    }
};

// Updated 2024-08-12
export const guess_file_extension = function guess_file_extension(
    filename_string: string
) {
    // console.log('*** guess_file_extension() ***');
    if (!filename_string) {
        return '';
    }

    if (!filename_string.includes('.')) {
        return '';
    }

    const file_extension =
        filename_string.substring(
            filename_string.lastIndexOf('.') + 1,
            filename_string.length
        ) || filename_string;
    // console.log(file_extension);
    return file_extension;
};

// Updated 2024-08-12
export const get_file_hash = async function get_file_hash(
    file: File
): Promise<string> {
    return new Promise((resolve, reject) => {
        const file_reader = new FileReader();

        file_reader.onload = async function () {
            const result = file_reader.result;
            if (!result || typeof result === 'string') {
                console.log(
                    'File was not read completely or is in wrong format'
                );
                reject('Error reading the file');
                return;
            }

            if (result.byteLength !== file.size) {
                console.log('File was not read completely');
                reject('Error reading the file');
                return;
            }

            const hash_buffer = await crypto.subtle.digest('SHA-256', result);
            const hash_array = Array.from(new Uint8Array(hash_buffer));
            const hash_hex = hash_array
                .map((b) => b.toString(16).padStart(2, '0'))
                .join('');

            resolve(hash_hex);
        };

        file_reader.readAsArrayBuffer(file);
    });
};
