#-*- coding:utf-8 -*-

import codecs
import datetime
import HTMLParser
import os
import tarfile

from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.utils.encoding import smart_str

from dictionary.models import Lemma, WalentyStat, get_ready_statuses
from settings import WALENTY_PATH

class Command(BaseCommand):
    args = 'none'
    help = 'Script for creating Walenty vocabulary in tex format.'

    def handle(self, *args, **options):
        try:
            now = datetime.datetime.now().strftime('%Y%m%d')
            filename_base = '%s_%s' % ('walenty', now)
            base_path = os.path.join(WALENTY_PATH, filename_base)
            outpath = base_path + '.tex'
            ready_statuses = get_ready_statuses()
            lemmas = Lemma.objects.filter(old=False)
            ready_lemmas = lemmas.filter(status__in=ready_statuses).order_by('entry_obj__name')
            write_tex_walenty(outpath, ready_lemmas)
            archive = tarfile.open(base_path + '-tex.tar.gz', 'w:gz')
            os.chdir(WALENTY_PATH)
            archive.add(os.path.basename(outpath))
        finally:
            archive.close()
            os.remove(outpath)
            

def write_tex_walenty(outpath, lemmas):
    try:
        outfile = codecs.open(outpath, 'w')
        h = HTMLParser.HTMLParser()
        outfile.write(smart_str(h.unescape(render_to_string('tex/slowal.tex', {'lemmas': lemmas, 
                                                                               'q_frame_opinions': [],
                                                                               'download_dict'   : {'frame_opinions': []},
                                                                               'frames_count'    : WalentyStat.objects.get(label=u'Łączna liczba ram semantycznych').value,
                                                                               'schemata_count'  : WalentyStat.objects.get(label=u'Łączna liczba schematów').value,
                                                                               'lemmata_count'   : WalentyStat.objects.get(label=u'Łączna liczba haseł').value}))))
    finally:
        outfile.close()
