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

# Copyright 2008-2010 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 format.bind import bind

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

    """
    _comment = "#"
    configName = "dovecot"
    configVersion = "0.1"
    __openArea = "{"
    __closeArea = "[ \t]*\}[ \t]*"
    sepFields = "\n"
    reOpen = re.compile(__openArea)
    reClose = re.compile(__closeArea)
    reCloseArea = re.compile(__closeArea + "\s*\Z")
    reComment = re.compile("[ \t]*%s" %(_comment))
    reSepFields = re.compile(sepFields)
    # разделитель названия и значения переменной
    reSeparator = re.compile("\s*=\s*")

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

    def postXML(self, xmlArea=False):
        """Последующая постобработка XML"""
        # Добавляем перевод строки если его нет в конец области
        if not xmlArea:
            xmlArea = self.docObj.body
        xmlFields = xpath.Evaluate("child::field", xmlArea)
        if xmlFields and not (\
            self.docObj.getTypeField(xmlFields[-1]) == "br" or\
                self.docObj.getTypeField(xmlFields[-1]) == "comment"):
            xmlArea.appendChild(self.docObj.createField("br",
                                                        [],"",[],
                                                        False,False))
        xmlAreas = xpath.Evaluate("child::area", xmlArea)
        for area in xmlAreas:
            self.postXML(area)

    def join(self, dovecotObj):
        """Объединяем конфигурации"""
        if isinstance(dovecotObj, dovecot):
            self.docObj.joinDoc(dovecotObj.doc)
            # Для добавления перевода строки перед закрывающим тегом
            # конфигурационного файла
            self.postXML()

 
