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 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)
            indexer = ContentIndexer(contentList, writer)
            indexer.index_all()
        else:
            self.stdout.write('Creating contents index...\n')
            contentList = Content.objects.all()
            indexer = ContentIndexer(contentList, writer)
            indexer.index_all()
                    
        if options.projects:
            self.stdout.write('Creating projects index...\n')
            projectList = Project.objects.filter(contents__in=contentList, state=2).distinct() 
            indexer = ProjectIndexer(projectList, writer)
            indexer.index_all()
        
        writer.close()
