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

# Copyright 2008-2016 Mir Calculate. 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 calculate.lib.cl_xml import xpath
from calculate.lib.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 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()

    def setDataField(self, txtLines, endtxtLines):
        """Создаем список объектов с переменными"""

        class fieldData:
            def __init__(self):
                self.name = False
                self.value = False
                self.comment = False
                self.br = False

        fields = []
        field = fieldData()
        z = 0
        for k in txtLines:
            textLine = k + endtxtLines[z]
            z += 1
            findComment = self.reComment.search(textLine)
            if not textLine.strip():
                field.br = textLine
                fields.append(field)
                field = fieldData()
            elif findComment:
                field.comment = textLine
                fields.append(field)
                field = fieldData()
            else:
                pars = textLine.strip()
                nameValue = self.reSeparator.split(pars)
                if len(nameValue) == 1 and \
                        (nameValue[0].startswith("!include") or
                             nameValue[0][1:].startswith("!include")):
                    field.name = textLine.replace(self.sepFields, "")
                    field.value = ""
                    field.br = textLine
                    fields.append(field)
                    field = fieldData()
                elif len(nameValue) == 1:
                    field.name = ""
                    field.value = textLine.replace(self.sepFields, "")
                    field.br = textLine
                    fields.append(field)
                    field = fieldData()

                elif len(nameValue) > 2:
                    valueList = nameValue[1:]
                    nameValue = [nameValue[0], " ".join(valueList).replace(
                        self.sepFields, "")]
                if len(nameValue) == 2:
                    name = nameValue[0]
                    value = nameValue[1].replace(self.sepFields, "")
                    field.name = name.replace(" ", "").replace("\t", "")
                    field.value = value
                    field.br = textLine
                    fields.append(field)
                    field = fieldData()
        return fields

    def createFieldTerm(self, name, value, quote, docObj):
        """Создание поля переменная - значение

        при создании поля проверяется первый символ названия переменной
        и добавляется тег action
        "!" - <action>drop</action> удаляет
        "+" - <action>join</action> добавляет
        "-" - <action>replace</action> заменяет
        """
        fieldAction = False
        if name:
            if name.startswith("!include") or name[1:].startswith("!include"):
                prefix = "!"
                name = re.sub(r"(include)\s*(\S)", r"\1 \2", name[1:])
            else:
                prefix = ""
            if name[0] == "!" or name[0] == "-" or name[0] == "+":
                qnt = self.removeSymbolTerm(quote)
                fieldXML = docObj.createField("var", [qnt],
                                              prefix + name[1:], [value],
                                              False, False)
                if name[0] == "!":
                    fieldAction = "drop"
                elif name[0] == "+":
                    fieldXML.setAttribute("type", "seplist")
                    fieldAction = "join"
            else:
                fieldXML = docObj.createField("var",
                                              [quote.replace("\n", "")],
                                              prefix + name, [value],
                                              False, False)
        else:
            fieldXML = docObj.createField("var",
                                          [quote.replace("\n", "")],
                                          name, [value],
                                          False, False)
        if fieldAction:
            docObj.setActionField(fieldXML, fieldAction)
        return fieldXML
