# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

import os

from typing import List

from .common import is_image, scan_sets
from .pbr_entry import PBREntry
from .pbr_directory import PBRDirectory

_epbr_postfixes = '[1k],[2k],[4k],[8k]'.split(',')
_epbr_options = '05k,1k,2k,4k,8k'.split(',')

class PBRExtremeScannerVault:
    """
    Scan PBR sets from ExtremePBR directory.
    """
    @staticmethod
    def scan(path: str) -> List[PBRDirectory]:
        r = [] # type: List[PBRDirectory]

        for _f in os.listdir(path):
            if _f.startswith('.'):
                continue

            # Full path.
            f = os.path.join(path, _f)

            # EPBR sets are organized in a linear directory.
            if os.path.isdir(f):
                d = PBRDirectory(_f, f)
                PBRExtremeScannerVault._scan_path(d)

                # If a least one set has been discovered,
                # add to sets.
                if d.has_sets():
                    r.append(d)

        r = sorted(r, key=lambda d: d.name)

        return r


    def _scan_path(dir: PBRDirectory):
        """
        Scan category.
        """
        # Loop over all content entries.
        for _f in os.listdir(dir.path):
            # Full path.
            f = os.path.join(dir.path, _f)
            if os.path.isdir(f):
                PBRExtremeScannerVault._scan_texture(_f, f, dir)

        # Finally sort items.
        dir.entries = sorted(dir.entries, key=lambda d: d.name)


    def _scan_texture(pbr: str, path: str, dir: PBRDirectory):
        """
        Scan a single texture.
        """
        # Loop over all sizes.
        variants = [] # type: List[PBREntry]
        for o in _epbr_options:
            f = os.path.join(path, o)
            if os.path.isdir(f):
                # Collect files in set folder.
                files = []
                for _sf in os.listdir(f):
                    sf = os.path.join(f, _sf)
                    if os.path.isfile(sf):
                        # Add just images.
                        if is_image(os.path.splitext(sf)[1].lower()):
                            files.append(sf)

                # If the subfolder [1k], [2k], .. has images ..
                if files:
                    # Scan the PBR set.
                    sets = scan_sets(files)
                    if len(sets) == 1:
                        # We found one.
                        s = sets[0]

                        s.name = pbr
                        s.variant_name = o

                        # Adjust preview image.
                        preview_path = os.path.join(path, 'data', 'previews', 'default')
                        # Try our recreated on first.
                        s.preview = os.path.join(preview_path, f'{pbr}.jpg')
                        if not os.path.exists(s.preview):
                            s.preview = os.path.join(preview_path, f'{pbr}.png')

                        # Add to this category.
                        variants.append(s)

        if variants:
            dir.entries.append(variants[0])
            if len(variants) > 1:
                variants[0].variants.extend(variants[1:])
