# 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


_epbr_prefixes = '[1k],[2k],[4k],[8k]'.split(',')


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

        for _f in os.listdir(path):
            # 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)
                PBRExtremeScannerOld._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


    @staticmethod
    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):
                # Collect files in set folder.
                files = []
                for _sf in os.listdir(f):
                    sf = os.path.join(f, _sf)
                    if os.path.isfile(sf):
                        files.append(sf)

                # Should result in a single set.
                sets = scan_sets(files)
                if len(sets) == 1:
                    s = sets[0]

                    # Adjust preview image.
                    pn = _f
                    for pf in _epbr_prefixes:
                        if pn.lower().startswith(pf):
                            pn = pn[len(pf):]
                    # Try our recreated on first.
                    s.preview = os.path.join(dir.path, f'{pn}.jpg')
                    if not os.path.exists(s.preview):
                        s.preview = os.path.join(dir.path, f'{pn}.png')

                    dir.entries.append(s)

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