"""
Management command used to generate all data and image items that are out of date.
This should be run by a cron job and uses a lock file so multiple copies don't run at the same time.
"""
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 all data and image items that are out of date.
    """
    help = "Generate all data and image items that are out of date."

    option_list = BaseCommand.option_list + (
        make_option('--force',
            action='store_true',
            dest='force',
            default=False,
            help='force regenerate of data and images'),
        )

    def handle(self, *args, **options):
        """
        For all PDFs, check whether their data and images are older than the PDF 'modified' time.
        If they are older, we re-generate just those items.
        """
        
        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:
            pdfs = Pdf.objects.order_by('-modified')
            force = options.get('force',False)

            for pdf in pdfs: # pylint: disable-msg=E1101
                if pdf.source:
                    if force or not pdf.check_data():
                        pdf.generate_pdf_data()
                    if force or not pdf.check_images():
                        pdf.generate_images()

        finally:
            lock.release()

