# 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
from .brush_directory import BrushDirectory
from .brush_entry import BrushEntry
from .abstract_scanner import AbstractScanner


class BrushLinearScanner:
    """
    Scans gray images (including 4 channel packed)
    recursively from directory.
    """
    @staticmethod
    def scan(path: str) -> List[BrushDirectory]:
        t = BrushDirectory('<ROOT>', path)
        BrushLinearScanner._scan_path(t)

        # Flatten to list.
        r = [] # type: List[BrushDirectory]
        AbstractScanner.flatten(t, r, [], True)
        r = sorted(r, key=lambda d: d.name)

        return r


    @staticmethod
    def _scan_path(dir: BrushDirectory):
        """
        Recursively scan all paths for gray textures.
        """
        # Loop over all content entries.
        for _f in os.listdir(dir.path):
            # Full path.
            f = os.path.join(dir.path, _f)

            # Whether it's a file or dir, either store file
            # or scan recursively.
            if os.path.isfile(f):
                # Filter, so just gray images (no previews) are in the list.
                n, ex = os.path.splitext(_f)

                # Image file?
                if is_image(ex.lower()): 
                    # Is no preview image?
                    if not n.lower().endswith('_preview'):
                        dir.entries.append(BrushEntry(
                            n,
                            os.path.join(dir.path, f'{n}_preview.jpg'),
                            f
                        ))

            elif os.path.isdir(f):
                d = BrushDirectory(_f, f)
                BrushLinearScanner._scan_path(d)
                # Add only if contains at least on element.
                if not d.empty():
                    dir.subdirs.append(d)

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