"""
Management command used to create entries in the Section model.

Expects two arguments:

    1. Slug of the PDF.
    2. Path to text file containing Table of Contents information in the form:

        [page_number]\t[section_title]

The command deletes all section information for the pdf!!
The command reads through the Table of Contents information and creates
section entries with the following information:

    Name
    PDF (ForeignKey)
    Slug (based on name)
    Abstract boolean flag
    Hidden boolean flag
    Mandatory boolean flag
    Start page number
    End page number
    Order
"""
from django.core.management.base import BaseCommand
from django.template.defaultfilters import slugify
from optparse import make_option
from rldjango.apps.binder.models import Pdf, Section
from django.conf import settings

class Command(BaseCommand):
    """
    Management command used to generate initial Section information.
    """
    help = "Generate section information from text of Table of Contents."

    def handle(self, *args, **options):
        """
        Get the PDF name; Read in the Table of Contents text; Create initial Section info.
        """
        if len(args) == 2:
            try:
                pdf = Pdf.objects.get(slug=args[0])
            except Pdf.DoesNotExist:
                print('PDF with slug "%s" not found' % (args[0]))
                return
            try:
                toc_file = open(args[1],'r')
                toc = toc_file.readlines()
            except IOError, e:
                print('File "%s" read failed: %s' % (args[1], e))
                return

        print('Deleting existing sections for PDF "%s"' % (pdf))
        if pdf.cover:
            # Don't delete the cover Section or the PDF also gets deleted
            Section.objects.filter(pdf=pdf).exclude(pk=pdf.cover.id).delete()
        else:
            Section.objects.filter(pdf=pdf).delete()

        if Section.objects.filter(slug__exact='cover'):
            pass
        else:
            # Create dummy section to represent cover. 
            Section.objects.create(name='Cover',
                                   slug='cover',
                                   pdf=pdf,
                                   abstract = False,
                                   hidden = False,
                                   mandatory = True,
                                   start=1,
                                   end=1,
                                   order=1,
                                   extra='{}')

        # Create dummy section to replresent PDF-level in table of contents.
        Section.objects.create(name=pdf.name,
                               slug=slugify(pdf.name),
                               pdf=pdf,
                               abstract = True,
                               hidden = False,
                               mandatory = True,
                               start=1,
                               end=1,
                               order=2,
                               extra='{"toc_colour": "%s"}' % (pdf.interface_text_color))
        prev_title = ''
        prev_start = 1
        prev_flags = ''
        for counter, line in enumerate(toc, 3):
            flags, page, title = line.strip().split('|')
            page_num = int(page)
            if prev_title:
                Section.objects.create(name=prev_title,
                                       slug=slugify(prev_title),
                                       pdf=pdf,
                                       abstract = prev_flags[0] == 'A',
                                       hidden = prev_flags[1] == 'H',
                                       mandatory = prev_flags[2] == 'M',
                                       start=prev_start,
                                       end=page_num-1 if prev_start < page_num else page_num,
                                       order=counter,
                                       extra='{"text_colour" : "white" , "bg_colour" : "#692174" }')
            prev_title = title
            prev_flags = flags
            prev_start = page_num
        if prev_title:
            Section.objects.create(name=prev_title,
                                   slug=slugify(prev_title),
                                   pdf=pdf,
                                   abstract = prev_flags[0] == 'A',
                                   hidden = prev_flags[1] == 'H',
                                   mandatory = prev_flags[2] == 'M',
                                   start=prev_start,
                                   end=prev_start,
                                   order=len(toc)+1,
                                   extra='{}')
        print('Added %s Section objects.' % (len(toc)))
