# Django imports.
from django.core.management.base import BaseCommand
from django.conf                 import settings

# Project imports.
from viewer.utils import make_thumbnail, is_image_file

###########################################################################################
# Command subclass.                                                                       #
###########################################################################################


class Command(BaseCommand):
    """
    Assorted data fix and clean up commands for the Meters module.
    """

    def _make_missing_thumbnails(self, directory):
        """
        Goes through the GALLERY_ROOT directory recursively and creates a new thumbnail
        for each image that does not have a corresponding file (same name) in the THUMBNAILS_ROOT
        directory.
        """

        # Make a thumbnail for each file in the current directory.
        for image in [i for i in directory.iterdir() if i.is_file() and is_image_file(i)]:
            make_thumbnail(image)

        # Handle each sub-directory recursively.
        for subdir in [i for i in directory.iterdir() if i.is_dir()]:
            self._make_missing_thumbnails(subdir)

    def handle(self, *args, **options):
        try:
            self._make_missing_thumbnails(settings.GALLERY_ROOT)

        except KeyboardInterrupt:
            self.stderr.write(self.style.ERROR('\nInterrupted'))
