from django.core.management.base import BaseCommand
from ldt.ldt_utils.models import Content, Project
from ldt.ldt_utils.contentindexer import ContentIndexer, ProjectIndexer
from ldt.management.utils import show_progress
from optparse import make_option

class Command(BaseCommand):
    help = 'Create a new index for all contents'
    option_list = BaseCommand.option_list + (
        make_option("-p", "--projects",
                  dest="projects",
                  action="store_true",
                  help="Index projects in addition to contents"),
        make_option("-c", "--content",
                  dest="content_id",
                  action="store",
                  type="string",
                  help="Index only the content specified by CONTENT_ID."),
        make_option("-n", "--nocontent",
                  dest="no_content",
                  action="store_true",
                  help="Avoid index only the content specified by CONTENT_ID."),
        )

    def handle(self, *args, **options):
        content_id = options.get("content_id")
        projects = options.get("projects")
        no_content = options.get("no_content")
        
        if content_id:
            self.stdout.write('Creating index for %s\n' % content_id)
            contentList = Content.objects.filter(iri_id=content_id)
        else:
            self.stdout.write('Creating contents index...\n')
            contentList = Content.objects.all()
        count = contentList.count()
            
        if not no_content:            
            indexer = ContentIndexer(contentList, callback=(lambda i,o: show_progress(i+1, count, o.title.encode('ascii','ignore'), 50)))
            indexer.index_all()
                    
        if projects:
            self.stdout.write('Creating projects index...\n')
            projectList = Project.objects.filter(contents__in=contentList, state=2).distinct()
            count = projectList.count()
            indexer = ProjectIndexer(projectList, callback=(lambda i,o: show_progress(i+1, count, o.title.encode('ascii','ignore'), 50)))
            indexer.index_all()
