import time
from pathlib import Path

import axipy
from PySide2.QtCore import QObject, Signal
from axipy import provider_manager, Layer, Map, view_manager, Notifications

from rosreestrXml.ui.tools.KPT.egrn_tool.egrn_generate_new import EgrnImport
from rosreestrXml.ui.tools.KPT.factory_kpt import factoryKptObj
from rosreestrXml.ui.tools.KPT.kptTools.DbKptDirectory import KptСatalog
from rosreestrXml.ui.tools.OutDrv.DbDocuments import DocumentsDb
from rosreestrXml.ui.tools.OutDrv.ObjectToSave import DbGeoOgr, TypeGeometryProviderOgr
from rosreestrXml.ui.tools.utils.fileAdapter import DataSourceXml


class ImportKpT(QObject):
    updateProcess = Signal(float,float)
    updateFormatProgressBar = Signal(str,str)
    finished = Signal(int)
    def __init__(self,parent_cls):
        super(ImportKpT, self).__init__()
        self.__parent_cls=parent_cls

        self.__old_val_progress_local = 0
    def setParametrs(self,params):
        self.__params=params
    def __process_callback(self, complete_main,complete_local):
        # print('progress: {}, message: "{}", unknown {}'.format(complete, message,user_data))
        if self.__cancelProcess:
            return 0
        cur_progress_int=int(complete_local*100+0.5)
        if cur_progress_int>self.__old_val_progress_local:
            self.updateProcess.emit(complete_main * 100,cur_progress_int)
            self.__old_val_progress_local=cur_progress_int
        else:
            if cur_progress_int<self.__old_val_progress_local:
                self.__old_val_progress_local = cur_progress_int
                self.updateProcess.emit(complete_main * 100,complete_local*100)
        #time.sleep(0.001)
        # self.__parent.window.pr_bar.setValue(complete*100)
        # print(complete*100)
        return 1
    def __isCancel(self):
        self.__cancelProcess=True

    def setCancel(self):
        self.__cancelProcess = True
    def run(self):
        #count=len(self.__params['source'])
        self.__cancelProcess = False
        try:
            self.__parent_cls.disconnect(self.__isCancel)
        except:
            pass
        self.__parent_cls.cancelProcess.connect(self.__isCancel)
        self.__cancelProcess = False
        cls_sourceXml = DataSourceXml()
        count = cls_sourceXml.build(self.__params['source'])
        count = cls_sourceXml.count
        self.__list_layer=[]
        if count==0:
            self.finished.emit(100)
            return
        path_out=self.__params['out']
        dbCatalog = KptСatalog()
        dbDoc = None

        db = DbGeoOgr(dbCatalog)
        db.Create(path_out, TypeGeometryProviderOgr.GPKG)
        dbDoc = DocumentsDb(path_out)
        dbDoc.initDb()
        db.setDbDocuments(dbDoc)
        is_ok = 1
        for i in range(count):
            file_source, value_file = cls_sourceXml.getSource(i)
            name_file=str(Path(file_source).name)
            #self.updateFormatProgressBar.emit("Чтение данных .."+name_file+" %p%"," %p%")
            self.updateFormatProgressBar.emit("Чтение данных .." + name_file , " %p%")
            value_string_no_utf8 = value_file.replace('<?xml version="1.0" encoding="utf-8"?>', '')
            value_string_no_utf8 = value_string_no_utf8.replace('<?xml version="1.0" encoding="UTF-8"?>', '')
            value_string_no_utf8 = value_string_no_utf8.replace('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', '')
            objs_to_save = factoryKptObj(value_string_no_utf8, self.__params['properties_import'])

            if isinstance(objs_to_save,EgrnImport):
                objs_to_save.setParentCls(self,i)
                objs_to_save.setPathOut(path_out)
                objs_to_save.run()
                name_table_result=objs_to_save.NameTable
                cs_in_xml=objs_to_save.cs_in_xml
                if cs_in_xml is not None:
                    Notifications.push("Импорт xml","Координатная система источника:"+cs_in_xml, Notifications.Information)
                if name_table_result is not None:
                    self.__list_layer.append(name_table_result)
            else:
                if objs_to_save is None or len(objs_to_save) == 0:
                    continue
                count_obj_save=len(objs_to_save)
                self.__old_val_progress_local = 0
                self.updateProcess.emit(-1, 0)

                for j,save_obj in enumerate(objs_to_save):
                    self.updateFormatProgressBar.emit(None, save_obj.NameProcess + " %p%")
                    is_ok = self.__process_callback(i / count, j / count_obj_save)
                    if is_ok == 0:
                        break
                    db.Save(save_obj)
                    name_layer=save_obj.NameLayer
                    if isinstance(name_layer,str):
                        if not (name_layer in self.__list_layer):
                            self.__list_layer.append(name_layer)
                    if isinstance(name_layer,list):
                        for layer_name in name_layer:
                            if not (layer_name in self.__list_layer):
                                self.__list_layer.append(layer_name)
                self.updateProcess.emit(-1, 100)
                if is_ok == 0:
                    break
        db.Close()


        if len(self.__list_layer)>0:
            ''' Создаем карту '''
            list_tabs = []
            list_layers = []
            for tab_name in self.__list_layer:
                temp_tab=provider_manager.openfile(path_out, dataobject=tab_name)
                count =temp_tab.count()
                if count==0:
                    temp_tab.close()
                    continue
                #list_tabs.append(provider_manager.openfile(path_out, dataobject=tab_name))
                list_tabs.append(temp_tab)
                list_layers.append(Layer.create(list_tabs[-1]))
            map = Map(list_layers)
            mapview = view_manager.create_mapview(map)

        self.updateProcess.emit(100, 0)
        self.finished.emit(100)
    def run_test(self):
        count_main=100
        count_local=6
        self.__cancelProcess = False
        try:
            self.__parent_cls.disconnect(self.__isCancel)
        except:
            pass
        self.__parent_cls.cancelProcess.connect(self.__isCancel)
        self.__cancelProcess = False
        is_ok=1
        for i in range(count_main):
            self.updateFormatProgressBar.emit("Чтение данных .."+str(i)+" %p%"," %p%")
            time.sleep(0.01)
            self.__old_val_progress_local=0
            self.updateProcess.emit(-1, 0)
            for j in range(count_local):
                time.sleep(0.5)
                self.updateFormatProgressBar.emit(None, "Тип "+str(j)+" %p%")
                is_ok=self.__process_callback(i/count_main,j/count_local)
                if is_ok==0:
                    break
            self.updateProcess.emit(-1, 100)
            if is_ok==0:
                break
        self.finished.emit(100)


