from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
import textwrap

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('-e', '--editable', action='store_true', dest='editable',
            help=('Try to make the file easier to edit by hand afterwards. '
                  'WARNING: may not provide exact representation')),
    )
    args = '<filename> [year1 year2]'

    def handle(self, *args, **options):
        from django.db import models
        from pycon.core import safe_ascii_encode
        if len(args) == 0:
            raise CommandError('an output filename must be supplied.')
        if len(args) != 1 and len(args) != 3:
            raise CommandError('two years must be supplied for replacement.')

        try:
            models = models.get_app('restructuredtext')
        except (ImproperlyConfigured, ImportError), e:
            raise CommandError(
                "%s. Are you sure your INSTALLED_APPS setting is correct?" % e)

        editable = options.get('editable', False)

        f = file(args[0],'w')
        f.write('pages = [\n')
        current = models.FlatPageHistory.current.all()
        for page in current.order_by('django_flatpage.url').select_related():
            url = safe_ascii_encode(page.page.url)
            content = safe_ascii_encode(page.content)
            if len(args) == 3:
                if url.startswith('/'+args[1]+'/'):
                    url = '/'+args[2]+'/' + url[len(args[1])+2:]
                content = content.replace(args[1], args[2])
            url = repr(url)

            if editable:
                ## WARNING: may corrupt data :-()
                content = "r'''" + content + "'''"
            else:
                ## exact representation, but still wrapped for easier editing
                ## just not easiest editing.
                content = repr(content)
                quote = content[0]
                sep = content[0] + "\n    " + content[0]
                content = sep.join(textwrap.wrap(content, 195))
                if content[0] != quote:
                    content = content[1:-1]

            f.write('[ ' + url + ',\n    ')
            f.write(content + '],\n')
        f.write(']\n')
