import os
import tarfile

import oras.client
from oras.logger import setup_logger

setup_logger(quiet=True, debug=False)


def download_image(target, outdir):
    """
    Method to download vdb files from a oci registry
    """
    oras_client = oras.client.OrasClient()
    paths_list = oras_client.pull(
        target=target,
        outdir=outdir,
        allowed_media_type=[],
        overwrite=True,
    )
    for apath in paths_list:
        if apath.endswith(".tar.gz") or apath.endswith(".tar.xz"):
            with tarfile.open(apath, "r") as tarf:
                tarf.extractall(path=outdir)
            try:
                os.remove(apath)
            except OSError:
                pass
    return paths_list
