import json
import os
import re

from model.services import ImagesServiceModel
from typing import Dict


class ImagesService(ImagesServiceModel):

    def get_images(
        self,
        images_path,        # type: str
        totem_config_path   # type: str
    ):
        # type: (...) -> Dict

        images = {"navigations": {}, "products": {}, "images": {}, "videos": {}}

        if not images_path or not os.path.exists(images_path):
            return images

        for image_file in os.listdir(images_path):
            full_image_path = os.path.join(images_path, image_file)

            if not os.path.isfile(full_image_path) or not image_file.endswith(".png"):
                continue

            if image_file.startswith("NAV"):
                image_category = "navigations"
            elif image_file.startswith("PRT"):
                image_category = "products"
            else:
                continue

            nav_reference = int(re.findall(r'\d+', image_file)[0])
            image_url = str(os.path.join("sui", "images", image_file)).replace("\\", "/")

            images[image_category][nav_reference] = image_url

        if not totem_config_path or not os.path.exists(totem_config_path):
            return images

        config_file = open(totem_config_path, 'rb')
        data = json.load(config_file)
        images["images"] = data.get("images", {})
        images["videos"] = data.get("videos", {})

        return images
