"""Watch graphics/ for any *.svg change and regenerate the DIE_BACK/DIE_PIP/
DIE_OVERLAY blocks in dice/svg_data.py and the hold/free-hover CSS in
dice.css, in place.

Run with: python manage.py watchsvg
"""
import os

from django.core.management.base import BaseCommand
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer

from dice import svg_ingest


def _is_relevant(path):
    return path.endswith('.svg')


class SvgChangeHandler(FileSystemEventHandler):
    def __init__(self, stdout):
        self.stdout = stdout

    def on_any_event(self, event):
        paths = [event.src_path] + ([event.dest_path] if hasattr(event, 'dest_path') and event.dest_path else [])
        if event.is_directory or not any(_is_relevant(p) for p in paths):
            return
        self.stdout.write(f'{event.event_type}: {os.path.basename(event.src_path)}')
        output_path = svg_ingest.regenerate()
        self.stdout.write(f'Regenerated {output_path}')


class Command(BaseCommand):
    help = 'Watch graphics/ for any *.svg change and regenerate dice/svg_data.py and dice.css in place.'

    def handle(self, *args, **options):
        self.stdout.write(f'Watching {svg_ingest.GRAPHICS_DIR} for *.svg changes (Ctrl+C to stop)...')
        output_path = svg_ingest.regenerate()
        self.stdout.write(f'Initial regeneration written to {output_path}')

        observer = Observer()
        observer.schedule(SvgChangeHandler(self.stdout), str(svg_ingest.GRAPHICS_DIR), recursive=False)
        observer.start()
        try:
            observer.join()
        except KeyboardInterrupt:
            observer.stop()
            observer.join()
            self.stdout.write('\nStopped.')
