import time
import logging

from PySide2.QtCore import QThread, Signal

#from rosreestrXml.ui.tools.kptTools.KptObjXml import FactoryKpt
from rosreestrXml.ui.tools.KPT.kptTools.kpt_10 import parse

#from PkkXml.plugins.XmlPkk.ProcessKptSave import KptProcessSave

'''from PkkXml.plugins.XmlPkk.DbDocuments import DocumentsDb
from PkkXml.plugins.XmlPkk.DbKptDirectory import KptСatalog
from PkkXml.plugins.XmlPkk.ObjectToSave import DbGeoOgr, TypeGeometryProviderOgr
'''


class ProgressBarCallBack:
    __baseClsProgressBar=None
    def __init__(self,base_progress):
        self.__baseClsProgressBar=base_progress
    def SendValue(self,new_procent):
        return self.__baseClsProgressBar.statusProgressBar(new_procent)


class ExecutionProcess:
    __count=0
    __all_procent=0
    __coef_proc=1
    __start_proc=0
    def __init__(self,start_procent,procent):
        self.__start_proc=start_procent
        self.__all_procent=procent
        self.__coef_proc=(self.__all_procent-self.__start_proc)/100
    def setCount(self,count):
        self.__count=count
    @property
    def Count(self):
        return self.__count
    def run(self,callback_fun):
        pass
    def setProcentStart(self,procent_start):
        self.__start_proc=procent_start
    @property
    def StartProcent(self):
        return self.__start_proc
    def calcProcent(self,index):
        curent_procent=(index/self.__count)*100
        #common_procent=(curent_procent/self.__all_procent)*100
        return int(curent_procent*self.__coef_proc)+self.__start_proc
class Exec1(ExecutionProcess):
    def __init__(self,start_proc,com_proc=None):
        super().__init__(start_proc,com_proc)
    def run(self,dop_parm,callback_fun=None):
        #print("Run Process :"+str(self.Count)+" Start procent:"+str(self.StartProcent))
        for i in range(self.Count):
            time.sleep(0.5)
            cur_procent=self.calcProcent(i)
            print(i,cur_procent)
            if callback_fun is not None:
                isCancel=callback_fun.SendValue(cur_procent)
                if not isCancel:
                    print("Процесс прерван ")
                    return False
        return True
class BasicProcess(QThread):
    countChanged =Signal(int)
    endProcess=Signal(int)
    updateHead = Signal(str)
    updateNameProcess = Signal(str)
    __count=None
    __clsProgress=None

    def setClsProgressBar(self,cls_progressBar):
        self.__clsProgress=cls_progressBar
    def run(self):
        pass
    @property
    def Count(self):
        return self.__count

    @property
    def ClsProgressBar(self):
        return self.__clsProgress

class PkkXmlProcess(BasicProcess):
    __listProcess = None
    __dopProperty=None
    __db=None
    def __init__(self,baseDb=None):
        super().__init__()
        self.__db=baseDb
        self.__db.initDs()
        #self.initDb(pathbaseDb)
    '''def initDb(self,pathDb):
        self.__dbCatalog = KptСatalog()
        self.__dbDoc = DocumentsDb(pathDb)
        self.__db = DbGeoOgr(self.__dbCatalog)
        self.__db.Create(pathDb, TypeGeometryProviderOgr.GPKG)
        self.__db.setDbDocuments(self.__dbDoc)'''
    def setCoordSsStyle(self,cs_wkt,propert_style):
        self.__out_cs_wkr=cs_wkt
        self.__propertyStyle=propert_style
    @property
    def Count(self):
        return self.__count
    def setProcess(self,lst_process):
        self.__listProcess=lst_process
    @property
    def Process(self):
        return self.__listProcess
    def setDopProperty(self,property:dict):
        self.__dopProperty=property
    def statusProgressBar(self,i_procent):
        #print("statusProgressBar:"+str(i_procent))
        logging.debug("statusProgressBar:"+str(i_procent))
        if self.ClsProgressBar.isCancel:
            return False
        if self.ClsProgressBar.CurentValue>=i_procent:
            return True
        #print("Send :" + str(i_procent))
        logging.debug("statusProgressBar:" + str(i_procent))
        self.countChanged.emit(i_procent)
        return True
    def run(self):
        #print('Start 0')
        logging.debug('Start 0')
        if self.__listProcess is None or len(self.__listProcess)==0:
            self.endProcess.emit(0)
            return
        self.ClsProgressBar.setTextProcess(self.__listProcess[0].NameProcess)
        index = 0
        # QCoreApplication.processEvents()
        #print('Start')
        # self.ClsProgressBar().setTitle('Проверка')
        # self.ClsProgressBar().show()
        cls_call = ProgressBarCallBack(self)
        while index < len(self.__listProcess):
            time.sleep(1)
            #print(self.__listProcess[index])
            self.ClsProgressBar.setTextProcess(self.__listProcess[index].NameProcess)
            #print('Start Task '+str(index))
            self.__listProcess[index].run(self.__dopProperty,cls_call)
            index += 1
            #time.sleep(0.005)

            #self.countChanged.emit(index)
            # QCoreApplication.processEvents()
            #print(self.ClsProgressBar)
            #if self.ClsProgressBar().isCancel:
            #    break
            #print("End Run Process:"+str(index))
        # self.countChanged.emit(-1)
        if self.__db is not None:
            self.__db.Close()
        self.endProcess.emit(0)

class PkkXmlProcessFiles(BasicProcess):
    __listProcess = None
    __listProcessFile=None
    __dopProperty=None
    __propertySelectIport=None
    __db=None
    __default_step=10
    __countInXml=0
    def __init__(self,baseDb=None):
        super().__init__()
        self.__db=baseDb
        self.__db.initDs()
        #self.initDb(pathbaseDb)
    '''def initDb(self,pathDb):
        self.__dbCatalog = KptСatalog()
        self.__dbDoc = DocumentsDb(pathDb)
        self.__db = DbGeoOgr(self.__dbCatalog)
        self.__db.Create(pathDb, TypeGeometryProviderOgr.GPKG)
        self.__db.setDbDocuments(self.__dbDoc)'''
    def setCoordSysStyle(self,cs_wkt,propert_style):
        self.__out_cs_wkt=cs_wkt
        self.__propertyStyle=propert_style
    @property
    def Count(self):
        return self.__count
    def setProcess(self,lst_process,prop_import):
        self.__listProcess=lst_process
        self.__propertySelectIport=prop_import
        self.__countInXml=self.__prepareCount()*len(self.__listProcess)
        return self.__countInXml
    @property
    def Process(self):
        return self.__listProcess
    def setDopProperty(self,property:dict):
        self.__dopProperty=property
    def statusProgressBar(self,i_procent):
        print("statusProgressBar:"+str(i_procent))
        if self.ClsProgressBar.isCancel:
            return False
        if self.ClsProgressBar.CurentValue>=i_procent:
            return True
        print("Send :" + str(i_procent))
        self.countChanged.emit(i_procent)
        return True


    def __prepareCount(self):
        count_in_file=0
        lst_name=list(self.__propertySelectIport.keys())
        for name_proc in lst_name:
            if self.__propertySelectIport[name_proc]:
                count_in_file=count_in_file+1
        return count_in_file
    def getProcessFromXml(self,start_process,curent_Objxml):
        list_process=[]
        #start_process_count=self.__countInXml*id_process
        count_in_xml=0
        if self.__propertySelectIport['SpatialData']:
            style=self.__propertyStyle['SpatialData']
            from PkkXml.plugins.XmlPkk.ProcessKptSave import KptProcessSave
            start_proc=start_process
            end_proc=start_proc+self.__default_step
            #start_proc=start_process_count*self.__default_step
            #end_proc = start_process_count*self.__default_step+self.__default_step
            print(" Start % "+str(start_proc)+" end % "+str(end_proc))

            list_process.append(KptProcessSave(self.__db.PropertyDB, curent_Objxml[0].getObjSpatialDataToSave(self.__out_cs_wkt, style), start_process, start_process))
            start_process=start_process+self.__default_step

        return list_process,start_process
    def run(self):
        print('Start 0')
        
        if self.__listProcess is None or len(self.__listProcess)==0:
            self.endProcess.emit(0)
            return
        #self.ClsProgressBar.setTextProcess(self.__listProcess[0].NameProcess)
        index = 0
        # QCoreApplication.processEvents()
        print('Start')
        # self.ClsProgressBar().setTitle('Проверка')
        # self.ClsProgressBar().show()
        cls_call = ProgressBarCallBack(self)
        start_procent=0
        while index < len(self.__listProcess):
            ObjKpt = parse(self.__listProcess[index], True)

            #from PkkXml.plugins.XmlPkk.KptObjXml import FactoryKpt
            from rosreestrXml.ui.tools.kptTools.KptObjXml import FactoryKpt
            objXmlKpt = FactoryKpt(ObjKpt)
            curent_process_lst,start_procent=self.getProcessFromXml(start_procent,objXmlKpt)
            print(self.__listProcess[index])
            for cur_process in curent_process_lst:
                self.ClsProgressBar.setTextProcess(cur_process.NameProcess)
                print('Start Task '+str(index))
                cur_process.run(self.__dopProperty,cls_call)
            objXmlKpt=None
            ObjKpt=None
            index += 1
            #time.sleep(0.005)

            #self.countChanged.emit(index)
            # QCoreApplication.processEvents()
            print(self.ClsProgressBar)
            #if self.ClsProgressBar().isCancel:
            #    break
            print("End Run Process:"+str(index))
        print("End Run All:")
        self.endProcess.emit(0)
        # self.countChanged.emit(-1)
        if self.__db is not None:
            self.__db.Close()
        #self.endProcess.emit(0)