import { makeAutoObservable } from 'mobx';

import { getStorage, ref, getDownloadURL, listAll, FirebaseStorage } from "firebase/storage";
import axios from "axios";


export class PreloadImg {
    storage: FirebaseStorage;

    constructor(listOfFolders: string[], bucket: string, firebase: any) {
        this.storage = getStorage(firebase);

        const listOfPathToImages = listOfFolders.map(async (folder: string) => {
            const listRef = ref(this.storage, `${bucket}/${folder}`);

            const { items } = await listAll(listRef);

            return items.map((item: any) => item.fullPath);
        })

        Promise.all(listOfPathToImages).then(res => {
            const flattedList = res.flat()
            flattedList.map((link: string) => this.loadImage(link));
        })

        makeAutoObservable(this);
    }

    img: { [key: string]: any } = {};
    loadedDestination: any = [];

    private getLinkFromConfig = (config: any): string | undefined => {
        return config?.thumbnails?.img?.path;
    };

    private async loadImage(path: string) {
        try {
            if (!path || this.img[path]) return;
            const url = await getDownloadURL(ref(this.storage, path))
            let res;

            if (path.includes('.json')) {
                res = await axios.get(url)
            } else {
                const loading = new Image();
                loading.src = url;
            }

            this.img[path] = res?.data || url;
        } catch (e) {
            this.img[path] = {};
        }
    }

    getImage = (path: string) => {
        if (!path) return;
        if (!this.img[path]) void this.loadImage(path);

        return this.img[path];
    };

    startPreloadImage = async (config: any, destination: string) => {
        try {
            const link: string | undefined = this.getLinkFromConfig(config);

            if (!link || this.img[link]) return;

            await this.loadImage(link);

            this.loadedDestination = [...this.loadedDestination, destination];
        } catch (e) {
            this.loadedDestination = [...this.loadedDestination];
        }
    };
}
