#-*- coding: utf-8 -*-
'''
Created on Jan 25, 2013

@author: lennyn
'''

import subprocess
from schema import *
from lxml import etree
from lxml.builder import ElementMaker

teins = 'http://www.tei-c.org/ns/1.0'
xmlns = 'http://www.w3.org/XML/1998/namespace'
namespaces = {'tei':teins, 'xml':xmlns}

E = ElementMaker(namespace=teins, nsmap={None:teins, 'xml':xmlns})


def getTEIHeader():
    return E.teiHeader(
                E.fileDesc(
                    E.titleStmt(
                        E.title(u'TEI P5 encoded version of "Syntactic-Generative Dictionary of Polish Verbs"')
                    )
                )
            )

def getSemanticAtomicDescElem(desc):
    return E.string(desc)

def getSemanticAtomicAttrsElem(semAttrs):
    if len(semAttrs) > 1:
        res = E.vColl()
        for attr in semAttrs:
            res.append(E.symbol(value=attr))
        return res
    elif len(semAttrs) > 0:
#        print semAttrs
        return E.symbol(value=list(semAttrs)[0])

def getSemanticDescsElem(phrase):
    if len(phrase.semanticDescs) > 1:
        res = E.vAlt()
        for semDescs in phrase.semanticDescs:
            semDescsElem = getSemanticAtomicDescsElem(semDescs)
            if semDescsElem:
                res.append(semDescsElem)
        return res
    elif phrase.semanticDescs:
        return getSemanticAtomicDescsElem(list(phrase.semanticDescs)[0])
    else:
        return None

def getSemanticAttrsElem(phrase):
    #~ print 'attrs', phrase.semanticAttrs
    if len(phrase.semanticAttrs | phrase.semanticDescs) > 1:
        res = E.vAlt()
        for semAttrs in phrase.semanticAttrs:
            semAttrsElem = getSemanticAtomicAttrsElem(semAttrs)
            if semAttrsElem is not None:
                res.append(semAttrsElem)
        for desc in phrase.semanticDescs:
            res.append(getSemanticAtomicDescElem(desc))
        #~ for semDesc in phrase.semanticDescs:
            #~ res.append(E.string(semDesc))
        return res
    elif phrase.semanticAttrs:
        return getSemanticAtomicAttrsElem(list(phrase.semanticAttrs)[0])
    elif phrase.semanticDescs:
        return getSemanticAtomicDescElem(list(phrase.semanticDescs)[0])
    else:
        return None

def getSchemaElem(schema):
    if isinstance(schema, Schema):
        return E.seg(
             *[getSchemaElem(child) for child in schema.children],
             type='schema')
    elif isinstance(schema, ComplexElement):
        return E.seg(
             *[getSchemaElem(child) for child in schema.children],
             type=schema.type)
    elif isinstance(schema, Phrase):
        res = E.seg(
                     E.fs(
                          E.f(
                              E.symbol(value=schema.label),
                              name='label'
                              ),
                          ),
                     type='phrase')
        if (schema.semanticAttrs | schema.semanticDescs):
            #~ print schema.semanticAttrs
            res[0].append(E.f(getSemanticAttrsElem(schema), name='semanticAttributes'))
        #~ if (schema.semanticDescs):
            #~ res[0].append(E.f(getSemanticDescsElem(schema), name='semanticDescriptions'))
        return res
    elif isinstance(schema, Verb):
        return E.seg(type='VERB')
    elif isinstance(schema, TextElement):
        return E.seg(schema.text, type='text')

def getSenseElem(sense):
    res = E.sense(
                   getSchemaElem(sense.schema)
                   )
    if sense.example:
        citElement = E.cit(E.quote(sense.example))
        res.insert(0, citElement)
    if sense.definition:
        defElement = etree.Element('def')
        defElement.text = sense.definition
        res.insert(0, defElement)
    return res

def getEntryElem(entry):
    return E.entry(
            E.form(E.orth(entry.orth)),
            *[getSenseElem(sense) for sense in entry.senses])

def write_tree(root, path_to_save):
#    if not os.path.exists(path_to_save):
#        os.makedirs(path_to_save)
    file = open(path_to_save, 'w')
    xmlstr = etree.tostring(root, pretty_print=True, encoding='UTF-8', xml_declaration=True)
    file.write(xmlstr)
    file.close()
    subprocess.check_call('xmllint --format {0} | sponge {0}'.format(path_to_save), shell=True)

def writeDictionary(outputFile, entries):
    tree = E.TEI(
            getTEIHeader(),
            E.text(
                E.body(
                       *[getEntryElem(entry) for entry in entries]
                       )
                   )
            )
    write_tree(tree, outputFile)
