import {deleteObject, ref, uploadBytes, uploadString} from "firebase/storage";
import {Address} from "../typeDefinitions";
import {executeCallable} from "./firebase";
import {storage} from "./firebaseConfig";
import FirebaseQuery from "./firebaseQuery";
import {getGeoHash, pathToArr} from "./util";
import {FirebaseError} from "firebase/app";

const firebaseQuery = new FirebaseQuery();

export const deleteStorageItem = async (path: string[] | string) => {
    const toDeleteRef = ref(storage, ...(pathToArr(path) as [any]));
    return await deleteObject(toDeleteRef);
};

export const uploadFiles = async (files: any[]|any, path: string[] | string, fileType?: string) => {
    const fileArray = Array.isArray(files) ? files : [files];
    let final = 1;

    await Promise.all(
        fileArray.map(async (element) => {
            const pathString = typeof path === "string" ? path : path.join("/");
            const newPath = pathString.includes(".") ? pathString : pathString + "/" + element.name;

            const storageRef = ref(storage, newPath);

            console.log("FILE ELEMENT", element);

            if (typeof element === "string") {
                return await uploadString(storageRef, element, "base64", fileType ? {contentType: fileType} : undefined)
                .catch((e) => {
                    final = e;
                });
            }

            return await uploadBytes(storageRef, element).catch((e) => {
                final = e;
            });
        })
    );

    return final;
};

type FeedbackObject = {
    title: string,
    msg: string,
    path: string,
    uid: string,
    created: Date
}

export const submitFeedback = async (feedbackObject: FeedbackObject) => {
    await firebaseQuery.add(["feedback"], feedbackObject);
};

export const editPlacementStage = async (pId: string, prevStageId: number, nextStageId: number) => {
    return await executeCallable("placement-changePlacementStage", {...{pId, prevStageId, nextStageId}});
};

type PlacementObject = {
    oId: string,
    uid: string
}

export const addPlacement = async (data:PlacementObject, studentId:string, isDraft:boolean) => {
    console.log("uploadDate", data, studentId, isDraft);
    return await executeCallable("placement-propose", {...{data, studentId, isDraft}}).catch((e:FirebaseError) => {
        console.log("e", e.message);
        throw e;
    });
};

export const uploadProviderAddress = async (providerId: string, address: Address) => {
    const geoHash = await getGeoHash(address);
    await firebaseQuery.add(["addresses"], {...address, geoHash: geoHash, product: "providers", oId: providerId});
};
