# -*- 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 sys
import re
# import xml.dom.minidom
from lxml import etree
from ..cl_template import TemplateFormat
from ..cl_xml import firstChild
from ..cl_lang import setLocalTranslate

_ = lambda x: x
setLocalTranslate('cl_lib3', sys.modules[__name__])


class patch(TemplateFormat):
    """Класс для замены, добавления, удаления, строк в файле"""
    # root нода
    rootNode = False
    # Документ
    doc = False
    # Текст шаблона
    text = ""

    def prepare(self):
        # Создаем XML документ
        self.doc = self.textToXML()
        if self.doc is not None:
            self.rootNode = self.doc.getroottree().getroot()
        self.reFlags = 0

    def textToXML(self):
        """Создание из текста XML документа
        Храним xml в своем формате
        """
        if not self.text.strip():
            self.text = ''
        text = ('<?xml version="1.0" encoding="UTF-8"?>\n<patch>%s</patch>'
                % self.text)
        try:
            # self.doc = xml.dom.minidom.parseString(text)
            self.doc = etree.XML(bytes(bytearray(text, encoding='utf-8')))
        except Exception:
            return False
        return self.doc

    def setMultiline(self):
        self.reFlags |= re.M

    def setDotall(self):
        self.reFlags |= re.S

    def processingFile(self, textConfigFile, rootPath=None, nameFile=None):
        """Обработка конфигурационного файла"""
        if self.doc is None:
            self.setError(_("Failed to convert the text template to XML"))
            return False
        retTextConfigFile = textConfigFile
        tags = ["reg", "text"]
        dataList = []
        tagsIndex = 0
        regex = False
        for node in list(self.rootNode):
            # if node.nodeType == node.ELEMENT_NODE:
            if not node.tag == tags[tagsIndex]:
                self.setError(_("Incorrect template text"))
                return False
            if tagsIndex == 1:
                tagsIndex = 0
            else:
                tagsIndex += 1
            # регулярное выражение
            if node.tag == "reg":
                if firstChild(node) is not None:
                    reText = firstChild(node).text
                    if reText is None:
                        textNode = node.toxml()
                        self.setError(
                            _("Incorrect template text") + ": \n" +
                            "%s" % textNode)
                        return False
                else:
                    self.setError(
                        _("Incorrect text of template '<reg></reg>'"))
                    return False
                if not reText.strip():
                    self.setError(
                        _("Incorrect text of template '<reg>%s</reg>'")
                        % reText)
                    return False
                try:
                    regex = re.compile(reText, self.reFlags)
                except re.error:
                    self.setError(
                        _("Incorrect text of template '<reg>%s</reg>'")
                        % reText)
                    return False
            elif node.tag == "text" and regex:
                if firstChild(node) is not None:
                    text = firstChild(node).text
                    if text is None:
                        textNode = node.toxml()
                        self.setError(
                            _("Incorrect template text") + ": \n" +
                            "%s" % textNode)
                        return False
                else:
                    text = ""
                dataList.append((regex, text))
                regex = False
        for regex, text in dataList:
            # Замены в тексте конфигурационного файла
            retTextConfigFile = regex.sub(text, retTextConfigFile)
        return retTextConfigFile
