"""Seed the sign-in scene from the bundled static photographs.

The first sets were shipped as static files; once they live in the database
staff can add and remove them like anything else. Idempotent: a caption
already present is skipped, so re-running adds only what is new.
"""
import pathlib

from django.conf import settings
from django.core.files.base import ContentFile
from django.core.management.base import BaseCommand

from documents.models import LoginPhoto


class Command(BaseCommand):
    help = "Import static/login/<prefix>-N.jpg into the sign-in scene."

    def add_arguments(self, parser):
        parser.add_argument("--prefix", required=True,
                            help="the property's file prefix, e.g. sands")

    def handle(self, *args, **options):
        folder = pathlib.Path(settings.BASE_DIR) / "static" / "login"
        files = sorted(folder.glob("%s-*.jpg" % options["prefix"]))
        if not files:
            self.stdout.write(self.style.WARNING("  nothing matching in %s" % folder))
            return
        start = (LoginPhoto.objects.count() or 0) + 1
        added = 0
        for offset, path in enumerate(files):
            if LoginPhoto.objects.filter(caption=path.name).exists():
                continue
            photo = LoginPhoto(order=start + offset, caption=path.name)
            photo.image.save(path.name, ContentFile(path.read_bytes()), save=True)
            added += 1
        self.stdout.write(self.style.SUCCESS(
            "  imported %d of %d (total now %d)" % (added, len(files), LoginPhoto.objects.count())))
