import os
import sqlite3
import threading


def getMessage(code_error):
    if code_error==0:
        return "Отсутствует подключение"
    if code_error==1:
        return "Ошибка выполнения sql :"
    if code_error==2:
        return "Ошибка закрытия курсора :"
def RunSql(connectDb,sql):
    cursor = connectDb.cursor()
    message_erro=None
    result=None
    if cursor is None:
        return None,getMessage(0)
    try:
        result_x = cursor.execute(sql).fetchone()
    except:
        message_erro=getMessage(1)
    try:
        cursor.close()
    except:
        message_erro=getMessage(2)
    if result_x is not None and len(result_x)>0:
        result=result_x[0]
    return result,message_erro
def RunSqlNoResult(connectDb,sql,params):
    cursor = connectDb.cursor()
    message_erro = None
    result = True
    if cursor is None:
        return None, getMessage(0)
    try:
        cursor.execute(sql,params)
    except:
        result=False
        message_erro = getMessage(1)
    try:
        cursor.close()
    except:
        message_erro = getMessage(2)

    return result, message_erro
class KptСatalog:
    __nameDbFile='KptSpravochnik.db'
    __dbConnect=None
    __nameCategoryEarth='КатегорийЗемель'
    __nameLandType='НаименованияУчастков'
    __nameStateLand='СтатусЗУ'
    def __init__(self):
        path_module=os.path.dirname(os.path.abspath(__file__))
        path_db=os.path.join(path_module,self.__nameDbFile)
        print(threading.current_thread())
        self.__dbConnect=sqlite3.connect(path_db)
    def close(self):
        print(threading.current_thread())
        try:
            self.__dbConnect.close()
            self.__dbConnect=None
        except:
            print("Error close Catalog")
            pass
        return
    @property
    def IsOpenDb(self):
        return self.__dbConnect is not None
    '''
    Получение категории земель из справочника
    код категории 
    '''
    def getCategoryEarth(self,cod_category):
        child_code=cod_category[-7:]
        sql = "select name_cat from " + self.__nameCategoryEarth + " where category='" + child_code + "'"
        return RunSql(self.__dbConnect,sql)
        '''cursor = self.__dbConnect.cursor()
        sql ="select name_cat from "+self.__nameCategoryEarth+" where category='"+child_code+"'"
        result=cursor.execute(sql).fetchone()
        cursor.close()
        return result[0]
        '''
    '''
    Получение Вид земельного участка ( названия )
    '''
    def getNameLandType(self,code):
        sql = "select name from " + self.__nameLandType + " where code=" + str(code)
        return RunSql(self.__dbConnect, sql)
        '''cursor = self.__dbConnect.cursor()
        sql = "select name from " + self.__nameLandType + " where code=" + str(code)
        result = cursor.execute(sql).fetchone()
        cursor.close()
        return result[0]'''
    def getStateObjectZU(self,code):
        sql="select status From "+self.__nameStateLand+" where code="+str(code)
        return RunSql(self.__dbConnect, sql)
    ''' Получение Вида Оъекта'''
    def getTypeObject(self,code):
        sql = "select значение from ВидОбъектов where code='" + code+"'"
        return RunSql(self.__dbConnect, sql)
    ''' Получение единиц измерения по ОКЕИ '''

    def getUnit(self, codeOkei):
        sql = "select значение from ЕдиницыИзмерени where ОКЕИ=" + codeOkei
        return RunSql(self.__dbConnect, sql)
    ''' Получения названия документа по типу'''
    def getDocument(self,codeDoc):
        sql="select annotation from AllDocuments where code='"+codeDoc+"'"
        return RunSql(self.__dbConnect, sql)
    ''' Получение стиля '''
    def GetStyle(self,name_tab,name_layer):
        sql ='select mi_style from '+name_tab+" where name='"+name_layer+"'"
        return RunSql(self.__dbConnect, sql)
    def GetPropertiesKpt(self,name_kpt):
        sql ="select * from "+name_kpt
        cursor=self.__dbConnect.cursor()
        result=None
        try:
            result=cursor.execute(sql).fetchall()
        except Exception as ex:
            print(ex)
        finally:
            cursor.close()
        if result is None:
            return None
        property_list=[]
        for item in result:
            proper_value={}
            proper_value['alias']=item[0]
            proper_value['name'] = item[2]
            proper_value['style']=item[1]
            proper_value['enable']=False
            if item[3]==1:
                proper_value['enable'] = True
            property_list.append(proper_value)
        return property_list
    def updateTabStyle(self,name_tab,properties):
        sql="Update "+name_tab+" set mi_style=?,is_enable=? where description=?"
        for item in properties:
            param_style=item['style']
            param_enable=0
            if item['enable']:
                param_enable=1
            key_description=item['key']
            result,message=RunSqlNoResult(self.__dbConnect,sql,(param_style,param_enable,key_description))
        self.__dbConnect.commit()









