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."),
        )

    def handle(self, *args, **options):
        content_id = options.get("content_id")
        projects = options.get("projects")
        
        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()
        
        c = lambda i,o: show_progress(i+1, count, o.title, 50)
            
        indexer = ContentIndexer(contentList, callback=c)
        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()
            c = lambda i,o: show_progress(i+1, count, o.title, 50) 
            indexer = ProjectIndexer(projectList, callback=c)
            indexer.index_all()
