// to learn how to download a file, get/use file metadata, delete files, and list files see https://firebase.google.com/docs/storage/web/start
import {
    ref,
    uploadBytesResumable,
} from "firebase/storage";
import { SupportedFileExtension } from '../../utils/types';
import { storage } from "../initFirebase";

const _validExtension: { [e in SupportedFileExtension]: null } = {
    [SupportedFileExtension.CSV]: null,
    [SupportedFileExtension.JSON]: null
}
export const getValidExtensions = () => Object.keys(_validExtension);


export function startUploadFile(
    file: File | Blob,
    name: string,
    events: {
        onProgress?: (percent: number) => void,
        onError?: (error: any) => void,
        onComplete?: () => void,
    }
) {
    const {onProgress, onError, onComplete} = events;
    // create a storage ref
    const storageRef = ref(storage, name)

    // upload file
    const task = uploadBytesResumable(storageRef, file)

    // update progress bar
    task.on('state_changed',

        function progress(snapshot) {
            if (onProgress) {
                onProgress((snapshot.bytesTransferred / snapshot.totalBytes) * 100)
            }
        },

        function error(err) {
            if (onError) {
                onError(err)
            }
        },

        function complete() {
            if (onComplete) {
                onComplete()
            }
        }
    )

}