import { IdbLocalStorage } from "../Web/IdbLocalStorage"
import { Store, UIEventSource } from "../UIEventSource"

export interface ImageUploadArguments {
    featureId: string
    readonly author: string
    readonly blob: File
    readonly targetKey: string | undefined
    readonly noblur: boolean
    readonly location: [number, number]
    readonly layoutId: string
    readonly date: number
}

/**
 * The 'imageUploadQueue' keeps track of all images that should still be uploaded.
 * It is backed up in the indexedDB as to not drop images in case of connection problems
 */
export default class ImageUploadQueue {
    public static readonly singleton = new ImageUploadQueue()
    private readonly _imagesInQueue: UIEventSource<ImageUploadArguments[]>

    public readonly imagesInQueue: Store<ImageUploadArguments[]>

    private constructor() {
        this._imagesInQueue = IdbLocalStorage.Get<ImageUploadArguments[]>("failed-images-backup", {
            defaultValue: [],
        })
        this.imagesInQueue = this._imagesInQueue
    }

    public add(args: ImageUploadArguments) {
        this._imagesInQueue.data.push(args)
        console.log("Got args", args)
        this._imagesInQueue.ping()
    }

    public delete(img: ImageUploadArguments) {
        const index = this._imagesInQueue.data.indexOf(img)
        if (index < 0) {
            return
        }
        this._imagesInQueue.data.splice(index, 1)
        this._imagesInQueue.ping()
    }

    applyRemapping(oldId: string, newId: string) {
        let hasChange = false
        for (const img of this._imagesInQueue.data) {
            if (img.featureId !== oldId) {
                continue
            }
            img.featureId = newId
            hasChange = true
        }
        if (hasChange) {
            this._imagesInQueue.ping()
        }
    }
}
