# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/098_Test_Dependencies.ipynb.

# %% auto 0
__all__ = ['logger', 'kafka_version', 'kafka_fname', 'kafka_url', 'local_path', 'tgz_path', 'kafka_path', 'check_java',
           'check_kafka', 'generate_app_src', 'generate_app_in_tmp']

# %% ../../nbs/098_Test_Dependencies.ipynb 2
import shutil
import tarfile
from contextlib import contextmanager
from os import environ
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import *

from .helpers import change_dir, in_notebook
from .logger import get_logger

if in_notebook():
    from tqdm.notebook import tqdm
else:
    from tqdm import tqdm

# %% ../../nbs/098_Test_Dependencies.ipynb 4
logger = get_logger(__name__)

# %% ../../nbs/098_Test_Dependencies.ipynb 6
def check_java(*, potential_jdk_path: Optional[List[Path]] = None) -> bool:
    if potential_jdk_path is None:
        potential_jdk_path = list(Path(environ["HOME"] + "/.jdk").glob("jdk-11*"))

    if potential_jdk_path != []:
        logger.info("Java is already installed.")
        if not shutil.which("java"):
            logger.info("But not exported to PATH, exporting...")
            environ["PATH"] = environ["PATH"] + f":{potential_jdk_path[0]}/bin"
        return True
    return False

# %% ../../nbs/098_Test_Dependencies.ipynb 8
def _install_java() -> None:
    """Checks if jdk-11 is installed on the machine and installs it if not
    Returns:
       None
    """
    try:
        import jdk
    except Exception as e:
        msg = "Please install test version of fastkafka using 'pip install fastkafka[test]' command"
        logger.error(msg)
        raise RuntimeError(msg)

    if not check_java():
        logger.info("Installing Java...")
        logger.info(" - installing jdk...")
        jdk_bin_path = jdk.install("11")
        logger.info(f" - jdk path: {jdk_bin_path}")
        environ["PATH"] = environ["PATH"] + f":{jdk_bin_path}/bin"
        logger.info("Java installed.")

# %% ../../nbs/098_Test_Dependencies.ipynb 10
# ToDo: move it somewhere
kafka_version = "3.3.2"
kafka_fname = f"kafka_2.13-{kafka_version}"
kafka_url = f"https://dlcdn.apache.org/kafka/{kafka_version}/{kafka_fname}.tgz"
local_path = Path(environ["HOME"]) / ".local"
tgz_path = local_path / f"{kafka_fname}.tgz"
kafka_path = local_path / f"{kafka_fname}"


def check_kafka(kafka_path: Path = kafka_path) -> bool:
    if (kafka_path / "bin").exists():
        logger.info("Kafka is installed.")
        if not shutil.which("kafka-server-start.sh"):
            logger.info("But not exported to PATH, exporting...")
            environ["PATH"] = environ["PATH"] + f":{kafka_path}/bin"
        return True
    return False

# %% ../../nbs/098_Test_Dependencies.ipynb 11
def _install_kafka(
    *,
    kafka_url: str = kafka_url,
    local_path: Path = local_path,
    tgz_path: Path = tgz_path,
) -> None:
    """Checks if kafka is installed on the machine and installs it if not
    Returns:
       None
    """
    try:
        import requests
    except Exception as e:
        msg = "Please install test version of fastkafka using 'pip install fastkafka[test]' command"
        logger.error(msg)
        raise RuntimeError(msg)

    if not check_kafka():
        logger.info("Installing Kafka...")
        local_path.mkdir(exist_ok=True, parents=True)
        response = requests.get(
            kafka_url,
            stream=True,
        )
        try:
            total = response.raw.length_remaining // 128
        except Exception:
            total = None

        with open(tgz_path, "wb") as f:
            for data in tqdm(response.iter_content(chunk_size=128), total=total):
                f.write(data)

        with tarfile.open(tgz_path) as tar:
            for tarinfo in tar:
                tar.extract(tarinfo, local_path)

        environ["PATH"] = environ["PATH"] + f":{kafka_path}/bin"
        logger.info(f"Kafka installed in {kafka_path}.")

# %% ../../nbs/098_Test_Dependencies.ipynb 13
def _install_testing_deps() -> None:
    _install_java()
    _install_kafka()

# %% ../../nbs/098_Test_Dependencies.ipynb 15
def generate_app_src(out_path: Union[Path, str]) -> None:
    import nbformat
    from nbconvert import PythonExporter

    path = Path("099_Test_Service.ipynb")
    if not path.exists():
        path = Path("..") / "099_Test_Service.ipynb"
    if not path.exists():
        raise ValueError(f"Path '{path.resolve()}' does not exists.")

    with open(path, "r") as f:
        notebook = nbformat.reads(f.read(), nbformat.NO_CONVERT)
        exporter = PythonExporter()
        source, _ = exporter.from_notebook_node(notebook)

    with open(out_path, "w") as f:
        f.write(source)

# %% ../../nbs/098_Test_Dependencies.ipynb 17
@contextmanager
def generate_app_in_tmp() -> Generator[str, None, None]:
    with TemporaryDirectory() as d:
        src_path = Path(d) / "main.py"
        generate_app_src(src_path)
        with change_dir(d):
            import_str = f"{src_path.stem}:kafka_app"
            yield import_str
