import sqlite3


class DocumentsDb:
    __pathDb=None
    __connect=None
    __nameTable="Documents"
    def __init__(self,pathDb):
        self.__pathDb=pathDb
    @property
    def IsConnect(self):
        if self.__connect is None:
            return False
        return True
    def initDb(self):
        self.__connect = sqlite3.connect(self.__pathDb)
        if self.__connect is not None:
            self.createTable()
    def createTable(self):
        sql_create="CREATE TABLE Documents (  pind INTEGER,КодДокумента  TEXT(12),Название TEXT(500),Серия TEXT(45),Номер TEXT(45),Дата DATE )"
        sql_index="CREATE INDEX parantIndex ON Documents(pind);"
        cursor=self.__connect.cursor()
        try:
            cursor.execute(sql_create)
            cursor.execute(sql_index)
        except:
            pass
        finally:
            cursor.close()
    def insert(self,sql,values,isReturnId=False):
        cursor = self.__connect.cursor()
        result=None
        try:
            cursor.execute(sql, values)
            if isReturnId:
                row = cursor.fetchone()
                result = row if row else None
        except Exception as ex:
            #logger.exception("Error insert: " + sql)
            print(ex)
        finally:
            cursor.close()
        return result
    def Write(self,idParent,xmlDocuments):
        for doc in xmlDocuments.Document:
            self.WriteItem(idParent,doc)
        pass
    def WriteItem(self,pkParent,xmlDoc):
        list_value=[]
        list_value.append(pkParent)
        list_value.append(xmlDoc.CodeDocument)
        list_value.append(xmlDoc.Name)
        list_value.append(xmlDoc.Series)
        list_value.append(xmlDoc.Number)
        list_value.append(xmlDoc.Date)
        sql="Insert Into "+self.__nameTable+" (pind,КодДокумента,Название,Серия,Номер,Дата) VALUES(?,?,?,?,?,?)"
        cursor = self.__connect.cursor()
        try:
            cursor.execute(sql, tuple(list_value))
            self.__connect.commit()
        except sqlite3.Error as error:
            print("Failed to update sqlite table", error)

        finally:
            if (cursor):
                cursor.close()



    def runSqlNoResult(self,sql):
        cursor = self.__connect.cursor()
        try:
            cursor.execute(sql)
        except sqlite3.Error as error:
            print(error)
        finally:
            if (cursor):
                cursor.close()
    def existTable(self,name_table):
        sql="SELECT name FROM sqlite_master WHERE type='table' AND name='"+name_table+"'"
        result=self.select(sql)
        if len(result)==0:
            return False
        return True
    def runSqlScript(self,path_script_sql):
        retValue=False
        with open(path_script_sql, 'r',encoding="utf-8") as sql_file:
            sql_script = sql_file.read()
        cursor=self.__connect.cursor()
        try:
            cursor.executescript(sql_script)
            retValue = True
        except Exception as ex:

            print(ex)
        finally:
            cursor.close()
        return retValue
    def select(self,sql):
        cursor = self.__connect.cursor()
        out_data=[]
        try:
            cursor.execute(sql)
            records = cursor.fetchall()
            for row in records:
                out_data.append(row)
        except Exception as ex:
            print(ex)
        finally:
            cursor.close()
        return out_data
    def commit(self):
        self.__connect.commit()
    @property
    def Connection(self):
        return self.__connect
    def close(self):
        if self.__connect is not None:
            self.__connect.commit()
            self.__connect.close()

