from django.core.management.base import LabelCommand, CommandError
from ldt.ldt_utils.models import Content
from optparse import make_option
from django.db import transaction

class Command(LabelCommand):
    help = 'init front project for content'    
    option_list = LabelCommand.option_list + (
        make_option('--noinput', action='store_false', dest='interactive', default=True,
            help='Tells to NOT prompt the user for input of any kind.'),
        make_option('--all-yes', action='store_true', dest='allyes',
            default=False, help='Answer yes to all question'),
    )

    def handle_label(self, label, **options):
        
        interactive = options.get('interactive')
        allyes = options.get('allyes')
            
        try:   
            content = Content.objects.get_by_natural_key(label)
        except Content.DoesNotExist:
            raise CommandError("Content \"%s\" does not exists." % label)
        
        if content is None:
            raise CommandError("Content \"%s\" does not exists." % label)

        do_delete = allyes
        if interactive and (not do_delete) and content.front_project is not None:
            confirm = raw_input("""The content already has a front project. Do you want to delete it ?

    Type 'yes' to delete, or 'no' to keep: """)
            do_delete = (confirm == "yes")
        
        with transaction.commit_on_success():        
            if do_delete:
                fp = content.front_project
                content.front_project = None
                content.save()
                fp.contents.clear()
                fp.delete()
            
            content.create_front_project()
            self.stdout.write('Successfully created front project for content "%s"' % label)
        
    