import logging
import os

from docker import DockerClient

from .ContainerImage import ContainerImage
from .ContainerImageList import ContainerImageList
from .helm import run_helm_command

logger = logging.getLogger("otimages." + os.path.basename(__file__))


class AVTSImages(ContainerImageList):
    def __init__(
        self,
        docker_client: DockerClient,
        version: str,
        repository: str = "artifactory.otxlab.net",
        path: str = "/ot2-paas/avts",
        helm_base_url: str = "https://artifactory.otxlab.net/artifactory/ot2-helm/avts",
        helm_dir: str = "",
        latest: bool = False,
    ):
        self.version = version
        self.repository = repository
        self.docker_client = docker_client
        self.helm_base_url = helm_base_url
        self.path = path
        self.latest = latest

        if helm_dir == "":
            self.helm_dir = self.helm_base_url + "/aviator-stack-" + self.version + ".tgz"
        else:
            self.helm_dir = helm_dir

        self.images = self.__get_images()

    def __get_images(self):

        logger.info(
            "Running helm template for %s in %s",
            self.version,
            self.helm_dir,
        )

        command = f"helm template {self.helm_dir} | yq '..|.image? | select(.)' | sort -u | grep artifactory.otxlab.net | sed 's/artifactory.otxlab.net\/ot2-paas\/avts\///g'"
        images = run_helm_command(command)

        assert images != []

        all_images = []

        for image in images:
            name = image.split(":")[0]
            version = image.split(":")[1] if not self.latest else "latest"
            version_overwrite = version

            all_images.append(
                ContainerImage(
                    repository=self.repository,
                    path=self.path,
                    name=name,
                    version=version,
                    version_overwrite=version_overwrite,
                    docker_client=self.docker_client,
                )
            )

        return all_images
