
export const useFiles = () => {
    const supabase = useSupabaseClient()
    const toast = useToast()

    let bucket = "filesdev"

    const profileStore = useProfileStore()

    const uploadFiles = async (formData, files,tags, upsert) => {
        const uploadSingleFile = async (file) => {
            //Create File Entry to Get ID for Folder
            const {data:createdFileData,error:createdFileError} = await supabase
                .from("files")
                .insert({
                    tenant: profileStore.currentTenant,
                })
                .select()
                .single()

            if(createdFileError){
                console.log(createdFileError)
                toast.add({title: "Hochladen fehlgeschlagen", icon: "i-heroicons-x-circle", color: "rose", timeout: 10000})
            } else if(createdFileData) {
                //Upload File to ID Folder
                const {data:uploadData, error: uploadError} = await supabase
                    .storage
                    .from(bucket)
                    .upload(`${profileStore.currentTenant}/filesbyid/${createdFileData.id}/${file.name}`, file, {upsert: upsert})

                if(uploadError) {
                    console.log(uploadError)
                    console.log(uploadError.statusCode)

                    if(uploadError.statusCode === '400') {
                        console.log("is 400")
                        toast.add({title: "Hochladen fehlgeschlagen", description: "Die Datei enthält ungültige Zeichen", icon: "i-heroicons-x-circle", color: "rose", timeout: 10000})
                    } else if(uploadError.statusCode === '409') {
                        console.log("is 409")
                        toast.add({title: "Hochladen fehlgeschlagen", description: "Es existiert bereits eine Datei mit diesem Namen", icon: "i-heroicons-x-circle", color: "rose", timeout: 10000})
                    } else {
                        toast.add({title: "Hochladen fehlgeschlagen", icon: "i-heroicons-x-circle", color: "rose", timeout: 10000})

                    }
                } else if(uploadData) {
                    //Update File with Corresponding Path
                    const {data:updateFileData, error:updateFileError} = await supabase
                        .from("files")
                        .update({
                            ...formData,
                            path: uploadData.path,
                        })
                        .eq("id", createdFileData.id)

                    if(updateFileError) {
                        console.log(updateFileError)
                        toast.add({title: "Hochladen fehlgeschlagen", icon: "i-heroicons-x-circle", color: "rose", timeout: 10000})
                    } else {
                        const {data:tagData, error:tagError} = await supabase
                            .from("filetagmembers")
                            .insert(tags.map(tag => {
                                return {
                                    file_id: createdFileData.id,
                                    tag_id: tag
                                }
                            }))



                        toast.add({title: "Hochladen erfolgreich"})

                    }
                }
            }
        }

        if(files.length === 1) {
            await uploadSingleFile(files[0])
        } else if( files.length > 1) {

            for(let i = 0; i < files.length; i++){
                await uploadSingleFile(files[i])
            }

        }
    }

    const selectDocuments = async (sortColumn = null, folder = null) => {
        let data = []

        if(sortColumn !== null ) {
            data = (await supabase
                .from("files")
                .select('*, incominginvoice(*), project(*), vendor(*), customer(*), contract(*), plant(*), createddocument(*), vehicle(*), product(*), profile(*), check(*), inventoryitem(*)')
                .eq("tenant", profileStore.currentTenant)
                .not("path","is",null)
                .not("archived","is",true)
                .order(sortColumn, {ascending: true})).data
        } else {
            data = (await supabase
                .from("files")
                .select('*, incominginvoice(*), project(*), vendor(*), customer(*), contract(*), plant(*), createddocument(*), vehicle(*), product(*), profile(*), check(*), inventoryitem(*)')
                .eq("tenant", profileStore.currentTenant)
                .not("path","is",null)
                .not("archived","is",true)).data

        }

        if(data.length > 0){
            let paths = []
            data.forEach(doc => {
                paths.push(doc.path)
            })

            const {data: supabaseData,error} = await supabase.storage.from(bucket).createSignedUrls(paths,3600)

            data = data.map((doc,index) => {

                return {
                    ...doc,
                    url: supabaseData[index].signedUrl
                }
            })
        }

        //console.log(data)

        return data
    }

    const selectSomeDocuments = async (documentIds, sortColumn = null, folder = null) => {
        let data = null

        if(sortColumn !== null ) {
            data = (await supabase
                .from("files")
                .select('*, incominginvoice(*), project(*), vendor(*), customer(*), contract(*), plant(*), createddocument(*), vehicle(*), product(*), profile(*), check(*), inventoryitem(*)')
                .in("id",documentIds)
                .eq("tenant", profileStore.currentTenant)
                .not("path","is",null)
                .not("archived","is",true)
                .order(sortColumn, {ascending: true})).data
        } else {
            data = (await supabase
                .from("files")
                .select('*, incominginvoice(*), project(*), vendor(*), customer(*), contract(*), plant(*), createddocument(*, customer(*), contact(*)), vehicle(*), product(*), profile(*), check(*), inventoryitem(*)')
                .in("id",documentIds)
                .not("path","is",null)
                .not("archived","is",true)
                .eq("tenant", profileStore.currentTenant)).data

        }

        if(data.length > 0){
            let paths = []
            data.forEach(doc => {
                paths.push(doc.path)
            })

            const {data: supabaseData,error} = await supabase.storage.from(bucket).createSignedUrls(paths,3600)

            data = data.map((doc,index) => {

                return {
                    ...doc,
                    url: supabaseData[index].signedUrl
                }
            })
        }

        //console.log(data)

        return data
    }

    const selectDocument = async (id) => {
        const {data,error} = await supabase
            .from("files")
            .select('*')
            .eq("id",id)
            .single()

        const {data: supabaseData,error:supabaseError} = await supabase.storage.from(bucket).createSignedUrl(data.path,3600)

        return {
            ...data,
            url: supabaseData.signedUrl
        }
/*
        if(data.length > 0){
            let paths = []
            data.forEach(doc => {
                paths.push(doc.path)
            })

            const {data: supabaseData,error} = await supabase.storage.from(bucket).createSignedUrls(paths,3600)

            data = data.map((doc,index) => {

                return {
                    ...doc,
                    url: supabaseData[index].signedUrl
                }
            })
        }

        //console.log(data)

        return data[0]*/
    }

    return {uploadFiles, selectDocuments, selectSomeDocuments, selectDocument}
}