from django.core.management.base import BaseCommand
import ldt.indexation
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):
        parser = self.create_parser("reindex", "")
        options, _ = parser.parse_args()
        
        writer = ldt.indexation.get_writer(True)
                   
        if options.content_id:
            self.stdout.write('Creating index for %s\n' % options.content_id)
            contentList = Content.objects.filter(iri_id=options.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, writer, callback=c)
        indexer.index_all()
                    
        if options.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, writer, callback=c)
            indexer.index_all()
        
        writer.close()
