# -*- coding: utf-8 -*-

import os

from django.core.management.base import BaseCommand, CommandError
from django.template.loader import render_to_string

from ...models import *


class Command(BaseCommand):
    args = ''
    help = 'Generate all pending pdf requests'

    def handle(self, *args, **options):
        pdfgenreqs = PDFGenerationRequest.objects.filter(done=false)
        for pgr in pdfgenreqs:

            # generating the annotation file for ghostscript
            notes = Note.objects.filter(user=pgr.user, document=pgr.document, done=False)
            annot = render_to_string("script/annotation.txt", locals())
            f = open(os.path.join(settings.ANNOT_SCRIPT_ROOT, "annot_%d.txt" % (pgr.id)), "w")
            f.write(annot)
            f.close

            # # execute the ghostscript
            # echo gs -o {{output_file}} -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress
            # {{input_file}} {{annotation_file}}

            # set pdf generation request as done
            pgr.done = True
            pgr.save()
            self.stdout.write("Succesfully generate pdf")

            # raise CommandError('Poll "%s" does not exist' % poll_id)
