""" fedora download """
import os

from virt.qemutest.distro.core import FetchDistroCore, FetchNetinst

class FetchFedoraCloud(FetchDistroCore):
    """ class for fedora cloud image download """

    fedora = "https://download.fedoraproject.org/pub"

    def __init__(self, mirror = None, arch = None):
        super().__init__(arch)
        self.mirror = mirror
        if mirror is None:
            self.mirror = self.fedora

    def baseurl(self, release):
        subdir = 'releases'
        location = f'fedora/linux/{subdir}/{release}/Cloud/{self.arch}/images'
        return f'{self.mirror}/{location}/'

    def image_id(self, release):
        return f'fedora-{release}-{self.arch}-cloud'

    def find_image(self, release, pattern):
        index = self.baseurl(release)
        checksum_name = self.indexhtml_find_file(index, 'CHECKSUM')
        if checksum_name is None:
            return (None, None)
        print(f'# checksum file: {checksum_name}')
        checksum_url = f'{self.baseurl(release)}{checksum_name}'
        return self.checksum_find_latest(checksum_url, pattern)

    def fetch_image(self, release = 44, pattern = 'Generic', imgdir = 'distro'):
        print(f'# ----- fedora {release} ({pattern}) -----')
        (latest, checksum) = self.find_image(release, pattern)
        url = f'{self.baseurl(release)}{latest}'
        out = f'{imgdir}/{latest}'
        os.makedirs(imgdir, exist_ok = True)
        self.fetch_image_checksum(url, out, checksum)
        self.index_update(imgdir, self.image_id(release), latest, checksum)

class FetchFedoraUKICloud(FetchFedoraCloud):
    """ class for fedora uki cloud image download """

    def image_id(self, release):
        return f'fedora-uki-{release}-{self.arch}-cloud'

    def fetch_image(self, release = 44, pattern = 'UKI', imgdir = 'distro'):
        super().fetch_image(release, pattern, imgdir)

class FetchFedoraNetinst(FetchNetinst):
    """ class for fedora server netinst iso download """

    fedora = "https://download.fedoraproject.org/pub"

    def __init__(self, mirror = None, arch = None):
        if mirror is None:
            mirror = self.fedora
        super().__init__(mirror, arch)

    def baseurl(self, release):
        if release == 'rawhide':
            subdir = 'development'
        else:
            subdir = 'releases'
        location = f'fedora/linux/{subdir}/{release}/Everything/{self.arch}/os'
        return f'{self.mirror}/{location}/'
