# -*- coding: utf-8 -*-
'''
Created on Jul 31, 2013

@author: ymh
'''

from core.models import Term
from jocondelab.models import ContributableTerm, TagcloudTerm
from django.core.management.base import BaseCommand
from optparse import make_option

class Command(BaseCommand):
    
    help = "Import a list of term for inclusion in the tagcloud or available contributable terms"
    
    option_list = BaseCommand.option_list + (
        make_option('-c', '--clear',
            dest= 'clear',
            action= 'store_true',
            default= False,
            help= 'Clear table' 
        ),
        make_option('-t', '--tagcloud',
            dest= 'tagcloud',
            action= 'store_true',
            default= False,
            help= 'Store in TagCloud table instead of ' 
        ),
        make_option('-l','--lang',
            dest= 'language_code',
            default= None,
            help= 'Language Code. If not provided, the labels in the Term table will be used' 
        ),
        make_option('-f','--file',
            dest= 'file_name',
            default= None,
            help= 'Extract keywords from a text file instead of from command line args'
        ),
    )
    
    def handle(self, *args, **options):
        
        terms_to_add = None
        
        if args:
            terms_to_add = args
        
        file_name = options.get('file_name', None)
        if file_name:
            try:
                f = open(file_name, 'r')
                terms_to_add = [l.strip() for l in f.readlines()]
                f.close()
            except:
                print "Can't open file %s"%file_name
                
        if not terms_to_add:
            print "No terms to add"
            return
        
        is_tagcloud = options.get('tagcloud', False)
        DestinationModel = TagcloudTerm if is_tagcloud else ContributableTerm
        
        print "Target model is %s"%DestinationModel.__name__
                
        if options.get('clear', False):
            print "Clearing table"
            DestinationModel.objects.all().delete()
        
        language_code = options.get('language_code', None)
        
        for t in terms_to_add:
            if t:
                tt = t.split("|")
                label = tt[0]
                ts = Term.objects
                if language_code:
                    ts = ts.filter(dbpedia_fields__label=label,dbpedia_fields__language_code=language_code)
                else:
                    ts = ts.filter(label=label)
                if len(tt) > 1:
                    thesaurus = tt[1]
                    ts = ts.filter(thesaurus__label=thesaurus)
                print "%d term(s) found for label '%s'"%(ts.count(),t)
                for to in ts:
                    DestinationModel.objects.get_or_create(term=to)
