"""
Management command used to generate PDF data files (JS and parsed source data)
"""

from django.core.management.base import BaseCommand
from optparse import make_option
from rldjango.apps.binder.models import Pdf
from django.conf import settings
from rlextra.thirdparty.mailer.lockfile import FileLock, AlreadyLocked, LockTimeout

LOCK_WAIT_TIMEOUT = getattr(settings, "GENERATE_LOCK_WAIT_TIMEOUT", -1)

class Command(BaseCommand):
    """
    Management command used to generate PDF data files (JS and parsed source data)
    """
    help = "Generate PDF data files (JS and parsed source data)"

    option_list = BaseCommand.option_list + (
        make_option('--pdf', '-p', dest='pdf',
            help='Supply a slug name to generate data for an individual PDF'),
    )

    def handle(self, *args, **options):
        """
        For all sections call generate_pdf_data
        """
        
        lock = FileLock("generate")
        try:
            lock.acquire(LOCK_WAIT_TIMEOUT)
        except AlreadyLocked:
            print 'Generation job already running.'
            return
        except LockTimeout:
            print 'Generation job already running.'
            return
        
        try:
            pdf = options.get('pdf', None)
            if pdf:
                pdfs = Pdf.objects.filter(slug=pdf)
            elif len(args):
                pdfs = Pdf.objects.filter(slug=args[0])
            else:
                pdfs = Pdf.objects.order_by('-modified')

            for pdf in pdfs: # pylint: disable-msg=E1101
                if pdf.source:
                    pdf.generate_pdf_data()

        finally:
            lock.release()

