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

# Copyright 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
from calculate.lib.cl_template import TemplateFormat

from calculate.lib.cl_lang import setLocalTranslate

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


class sqlite(TemplateFormat):
    """
    Формат для модификации sqlite db файлов
    """
    text = ""

    def textToXML(self):
        return self.text

    def processingFile(self, textConfigFile, rootPath=None, nameFile=None):
        """Обработка конфигурационного файла"""
        try:
            import sqlite3
        except ImportError:
            self.setError(_("Format 'sqlite' is unavailable"))
            sqlite3 = None
            return False
        try:
            conn = sqlite3.connect(nameFile)

            for i, query in enumerate(self.text.split(";\n")):
                try:
                    conn.execute(query)
                    conn.commit()
                except (sqlite3.OperationalError, sqlite3.IntegrityError) as e:
                    if callable(self.parent.printWARNING):
                        self.parent.printWARNING("%s:%d: %s" % (
                            self.parent.nameFileTemplate, i, _(str(e))))
            conn.close()
        except (sqlite3.OperationalError, sqlite3.IntegrityError) as e:
            self.setError(_(str(e)))
            return False
        return ""
