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

# Copyright 2008-2012 Calculate Ltd. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import re
from xml import xpath
from calculate.lib.cl_template import xmlDoc
from calculate.lib.format.samba import samba

class kde(samba):
    """Класс для обработки конфигурационного файла типа kde

    """
    _comment = "#"
    configName = "kde"
    configVersion = "0.1"
    reHeader = re.compile("^[\t ]*\[[^\[\]]+\].*\n?",re.M)
    reBody = re.compile(".+",re.M|re.S)
    reComment = re.compile("^\s*%s.*"%(_comment))
    reSeparator = re.compile("=")
    sepFields = "\n"
    reSepFields = re.compile(sepFields)

    def __init__(self,text):
        samba.__init__(self,text)

    def removeSymbolR(self, text):
        """Удаляет первый символ названия переменной в строке

        Если первый встречающийся символ с начала строки
        '!' то он из этой строки будет удален,
        если перед этим символом были пробельные символы,
        то они будут сохранены, так-же если в строке есть символ
        перевода строки он будет удален.
        """
        reTerm = re.compile("^[ \t]*(\!)")
        textNS = text.replace("\n","")
        res = reTerm.search(textNS)
        if res:
            textNS = textNS[res.start():res.end()-1] + textNS[res.end():]
        return textNS

    def _textToXML(self):
        """Преобразует текст в XML"""
        blTmp = self.blocTextObj.findBloc(self.text,self.reHeader,self.reBody)
        blocs = self.getFullAreas(blTmp)
        headers = []
        startHeaders = []
        finHeaders = []
        docObj = xmlDoc()
        docObj.createDoc(self.configName, self.configVersion)
        rootNode = docObj.getNodeBody()
        # Если пустой текст то создаем пустой документ
        if not blocs:
            return docObj

        for h in blocs[0]:
            reH = re.compile("]\s*$")
            #listfinH = h.split("]")
            listfinH = reH.split(h)
            finH = listfinH[0]
            if "[" in finH:
                startHeaders.append(finH + "]")
            else:
                startHeaders.append(finH)
            if len(listfinH) == 2:
                finHeaders.append(listfinH[1])
            else:
                finHeaders.append("")
            head=finH.replace("][",".").replace("[","").replace("]","").strip()
            headers.append(head)
        bodys = blocs[1]

        z = 0
        for h in headers:
            if not bodys[z]:
                z += 1
                continue
            areaAction = False
            if h:
                if h[0] == "!":
                    docObj.createCaption(h[1:], [startHeaders[z],""])
                    areaAction = "drop"
                elif h[0] == "-":
                    docObj.createCaption(h[1:], [startHeaders[z],""])
                    areaAction = "replace"
                else:
                    docObj.createCaption(h, [startHeaders[z],""])
            else:
                docObj.createCaption(h, [startHeaders[z],""])

            if "\n" in blocs[0][z]:
                if self.reComment.search(finHeaders[z]):
                        docObj.createField('comment', [finHeaders[z]])
                elif not finHeaders[z].strip() and\
                     finHeaders[z].replace("\n",""):
                        docObj.createField('br',
                                            [finHeaders[z].replace("\n","")])
                else:
                    docObj.createField('br')
            fields = self._splitToFields(bodys[z])
            for f in fields:
                if f.name != False and f.value!=False and f.br!=False:
                    # Обработка условий для kde
                    if f.name[0] == "!":
                        qns = self.removeSymbolR(f.br)
                        xmlField = docObj.createField("var",
                                                      [qns],
                                                      f.name[1:], [f.value])
                        # Удаляемое в дальнейшем поле
                        docObj.setActionField(xmlField, "drop")
                    else:
                        docObj.createField("var",[f.br.replace("\n","")],
                                           f.name, [f.value])
                    docObj.createField('br')
                elif f.comment != False:
                    docObj.createField('comment', [f.comment])
                elif f.br != False:
                    docObj.createField('br', [f.br.replace("\n","")])
            if h.strip():
                area = docObj.createArea()
                if areaAction:
                    docObj.setActionArea(area, areaAction)
                rootNode.appendChild(area)
            else:
                fieldsNodes = docObj.tmpFields.getFields()
                for fieldNode in fieldsNodes:
                    rootNode.appendChild(fieldNode)
                docObj.clearTmpFields()
            z += 1
        return docObj

    def join(self, kdeObj):
        """Объединяем конфигурации"""
        if isinstance(kdeObj, kde):
            self.docObj.joinDoc(kdeObj.doc)
            self.postXML()

 
