import io
import itertools
import re
import tarfile
from typing import AsyncIterable, Collection, Iterable, Tuple

from maps_adv.export.lib.config import config

AVATARS_ALIAS_TEMPLATE_REGEXP = re.compile(
    r"^(?P<alias>.+?)(_?\{(zoom|size)\})?$", re.IGNORECASE
)


async def tar_compressor(files: AsyncIterable[Tuple[str, bytes]], filename: str):
    with tarfile.open(filename, "w:gz") as tar:
        async for file_name, file_data in files:
            file_info = tarfile.TarInfo(file_name)
            file_info.size = len(file_data)
            tar.addfile(file_info, io.BytesIO(file_data))


def generate_image_filename_from_avatar(image: dict) -> str:
    namespace = config.AVATARS_NAMESPACE
    name = image["image_name"]
    group_id = image["group_id"]

    if "alias" in image:
        alias = image["alias"]

    else:
        alias = AVATARS_ALIAS_TEMPLATE_REGEXP.match(image["alias_template"]).group(
            "alias"
        )

    return f"{namespace}--{group_id}--{name}--{alias}"


def split_to_chunks(collection: Iterable, chunk_size: int) -> tuple:
    it = iter(collection)
    while True:
        chunk = tuple(itertools.islice(it, chunk_size))
        if not chunk:
            return
        yield chunk


def printable(collection: Collection) -> str:
    return ", ".join(map(str, collection))
