import {appPath, AsyncCollection, collect, Collection, Singleton, UniversalPath, universalPath} from '@extollo/lib'

export interface LXCImage {
    os: string
    version: string
    arch: 'amd64' | 'arm64' | 'i386' | string
    format: 'cloud' | 'default'
    timestamp: string
    endpoint: string
}

@Singleton()
export class Images {
    private imageServer = 'https://us.lxd.images.canonical.com'
    private listEndpoint = 'meta/1.0/index-system'
    private imageBinaryName = 'rootfs.tar.xz'

    public async getImages(): Promise<Collection<LXCImage>> {
        const url = universalPath(this.imageServer, this.listEndpoint)
        const content = await fetch(url.toRemote).then(x => x.text())
        return collect(content.trim().split('\n'))
            .map(row => {
                const [os, version, arch, format, timestamp, endpoint] = row.split(';')
                return {
                    os,
                    version,
                    arch,
                    format,
                    timestamp,
                    endpoint,
                } as LXCImage
            })
    }

    public getImageBinaryPath(image: LXCImage): UniversalPath {
        return universalPath(this.imageServer, image.endpoint, this.imageBinaryName)
    }
}
