export type FileInputToBase64FunctionReturn = {
    fileBase64?: string;
    fileBase64Full?: string;
    fileName?: string;
    fileSize?: number;
    fileType?: string;
    file?: File;
};

export type FileInputToBase64FunctioParam = {
    inputFile: File;
    allowedRegex?: RegExp;
};

export default async function fileInputToBase64({
    inputFile,
    allowedRegex,
}: FileInputToBase64FunctioParam): Promise<FileInputToBase64FunctionReturn> {
    const allowedTypesRegex = allowedRegex ? allowedRegex : undefined;

    if (allowedTypesRegex && !inputFile?.type?.match(allowedTypesRegex)) {
        window.alert(`We currently don't support ${inputFile.type} file type.`);
        return { fileName: inputFile.name };
    }

    let fileName = inputFile.name?.replace(/\..*/, "");
    const file = inputFile;

    try {
        const fileData: string | undefined = await new Promise(
            (resolve, reject) => {
                var reader = new FileReader();
                reader.readAsDataURL(inputFile);
                reader.onload = function () {
                    resolve(reader.result?.toString());
                };
                reader.onerror = function (/** @type {*} */ error: any) {
                    console.log("File Input to Base64 Error: ", error.message);
                };
            }
        );

        return {
            fileBase64: fileData?.replace(/.*?base64,/, ""),
            fileBase64Full: fileData,
            fileName: fileName,
            fileSize: inputFile.size,
            fileType: inputFile.type,
            file,
        };
    } catch (error: any) {
        console.log("File Processing Error! =>", error.message);

        return {
            fileName: inputFile.name,
            file,
        };
    }
}
