# 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 scan_sets
from .pbr_directory import PBRDirectory
from .abstract_scanner import AbstractScanner


class PBRLinearScanner:
    """
    Scans PBR sets in directories, where all set items (including preview)
    lie on the same directory level.
    """
    @staticmethod
    def scan(path: str) -> List[PBRDirectory]:
        t = PBRDirectory('<ROOT>', path)
        PBRLinearScanner._scan_path(t)

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

        return r
        

    @staticmethod
    def _scan_path(dir: PBRDirectory):
        """
        Recursively scan all paths for PBR sets.
        """
        # Collect here for later set scanning.
        files = [] # type: List[str]

        # 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 scen recursively.
            if os.path.isfile(f):
                files.append(f)
            elif os.path.isdir(f):
                d = PBRDirectory(_f, f)
                PBRLinearScanner._scan_path(d)
                # Add only if contains a least on element.
                if not d.empty():
                    dir.subdirs.append(d)

        # Build sets from files and add
        # to info.
        dir.entries.extend(scan_sets(files))

        # Finally adjust preview name for all sets.
        for s in dir.entries:
            s.preview = os.path.join(os.path.split(s.diffuse)[0], f'{s.name}_preview.jpg')

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