import os

import axipy
from PySide2.QtGui import QIcon
from axipy import AxiomaPlugin, state_manager, data_manager

from PySide2.QtWidgets import QMessageBox

from .toolprocessing.TopoToolProcessing import RunTopo

from .toolprocessing.ui.DlgProgressBar import DlgProgressBar
from .ui.DlgAddTableToMap import DlgAddTable
from .ui.DlgFormTopoCorrect import FormTopoCorrect
from .ui.DlgSnapNodes import DlgSnapNodes
from .ui.TopoUIToolsDbPointAreaPt import TopoTools
from .ui.Utils import getMapViewByName, getIdLayerinMap
from .ui.docWidget import AxiDocWidget, addDoc, existDocWidget, DelDocWidget
from ru_rubtsov_axioma_topo_tools.toolprocessing.add_helper.temp_folder import manager_temp_folder

class Plugin(AxiomaPlugin):
    def load(self):
        self.__topo_erorr_doc=None
        self.__form_correct=None
        self.__list_topo=[]
        name_observer="TopoCountTableVector"
        name_observer_correct_topo="TopoCorrect"
        self.__observer=None
        self.__observer_topo_correct=None
        try:
            self.__observer=axipy.observer_manager.get(name_observer)
        except:
            pass
        if self.__observer is None:
            self.__observer=axipy.Observer(name_observer,False)
        try:
            self.__observer_topo_correct=axipy.observer_manager.get(name_observer_correct_topo)
        except:
            pass
        if self.__observer_topo_correct is None:
            self.__observer_topo_correct=axipy.Observer(name_observer_correct_topo,False)

        axipy.da.data_manager.updated.connect(self.__isEvailabel)
        local_file_icon=os.path.join(os.path.dirname(os.path.realpath(__file__)),'ui', 'checkregions_32x32.png')
        self.__action = self.create_action('Проверка топологии',
                                           icon=local_file_icon, on_click=self.__run_tools,
                                           enable_on = name_observer)

        #axipy.da.catalog_service.removed.connect(self.__isCloseDataObject)
        data_manager.removed.connect(self.__isCloseDataObject)
        local_file_icon_correct=self.local_file("ui",'cleanobjects_32x32.png')
        self.__action_correct = self.create_action('Коррекция топологии',
                                           icon=local_file_icon_correct, on_click=self.__run_tools_correct,
                                           enable_on = name_observer_correct_topo)
        '''
        self.__action_snap = self.create_action('Совмещение узлов',
                                            on_click=self.__run_tools_snap_node,
                                           enable_on=name_observer)
        '''
        position = self.get_position("Таблица", "Проверка полигонов")
        position.add(self.__action)
        position.add(self.__action_correct)
        #position.add(self.__action_snap)

        self.__isEvailabel()

    def unload(self):

        if self.__topo_erorr_doc is not None:
            DelDocWidget(axipy.app.mainwindow.qt_object(), self.__topo_erorr_doc)
            self.__topo_erorr_doc = None
            self.__form_correct = None

        self.__action.remove()
        self.__action_correct.remove()
        manager_temp_folder.closeAll()

    def __isEvailabel(self):
        def isVector(obj):
            if not isinstance(obj, axipy.Table):
                return False
            return obj.is_spatial
        vectors = list(filter( isVector, axipy.da.data_manager.objects))
        if len(vectors)>0:
            self.__observer.value=True
        else:
            self.__observer.value=False
        if self.__observer.value:
            return
        self.__isCloseDataObject()
    def __isCloseDataObject(self,name_tab=None):
        #print("Close table")
        if len(self.__list_topo)==0:
            self.__observer_topo_correct.value=False
            self.__removeWidget()
            return
        index=0
        list_remove=[]
        for obj_topo in self.__list_topo:
            index = index + 1
            if name_tab is not None :
                if name_tab==obj_topo['source'] or name_tab==obj_topo['result']:
                    list_remove.append(index - 1)
                    continue
            tab_source=axipy.da.data_manager.find(obj_topo['source'])
            tab_topo=axipy.da.data_manager.find(obj_topo['result'])


            if (tab_topo is not None) and (tab_source is not None):
                continue
            list_remove.append(index-1)
        if len(list_remove)>0:
            for id in list_remove:
                self.__list_topo.pop(id)
        if len(self.__list_topo)>0:
            self.__observer_topo_correct.value=True
            if self.__form_correct is not None:
                self.__form_correct.update(self.__list_topo)
        else:
            self.__observer_topo_correct.value=False
            self.__removeWidget()
    def __run_tools_snap_node(self):
        cls_snap_dlg=DlgSnapNodes(axipy.mainwindow.qt_object())
        cls_snap_dlg.exec_()
    def __run_tools(self):
        dlg=TopoTools()
        dlg.show()
        bIsOk=dlg.isOk
        if not bIsOk:
            return
        property_for_check=dlg.PropertyesForCheckTopology
        table=axipy.app.mainwindow.catalog.find(property_for_check['table_source'])
        temp_mem_table=None
        #from ru_rubtsov_axioma_topo_tools.toolprocessing.add_helper.temp_folder import manager_temp_folder
        temp_mem_table = manager_temp_folder.create(table.name, table.coordsystem)
        base_task_topo=RunTopo(table,property_for_check,temp_mem_table)
        dlg_pr = DlgProgressBar(base_task_topo,axipy.app.mainwindow.qt_object())
        dlg_pr.setTextProcess("Проверка топологии")
        dlg_pr.setTitle("Проверка топологии")
        base_task_topo.setClsProgressBar(dlg_pr)

        dlg_pr.exec(100)
        table_topo_err=base_task_topo.ResultTable
        if table_topo_err is None:
            message=QMessageBox(axipy.app.mainwindow.qt_object())
            message.setWindowTitle("Проверка топологии")
            message.setText("Топологических ошибок не найдено")
            message.setStandardButtons(QMessageBox.Ok)
            message.exec()
            return
        angle_lim=None
        ''' Если была проверка углов вершин'''
        if property_for_check['angle_limit']['enable']:
            angle_lim=property_for_check['angle_limit']['angle_limit']
        self.__list_topo.append({"source":table.name,"result":table_topo_err.name,'angle_lim':angle_lim})
        if self.__form_correct is not None:
            self.__form_correct.update(self.__list_topo)
        self.__observer_topo_correct.value=True
        dlg_add_table=DlgAddTable(table_topo_err.name)
        dlg_add_table.show()
        name_map_view=dlg_add_table.nameMapView
        if name_map_view is None:
            return
        ''' Добавляем таблицу топологических ошибок в выбранную карту'''

        layer_err_topo= axipy.Layer.create(table_topo_err)
        map_view=getMapViewByName(name_map_view)
        if map_view is None:
            return
        map_view.map.layers.add(layer_err_topo)
        id_layer=getIdLayerinMap(map_view.map.layers,layer_err_topo.title)
        if id_layer>0:
            map_view.map.layers.move(id_layer, 0)
    def __run_tools_correct(self):
        mainwindowAxi=axipy.app.mainwindow.qt_object()
        if self.__form_correct is None:
            self.__form_correct=FormTopoCorrect()
        if self.__topo_erorr_doc is None:
            self.__topo_erorr_doc=AxiDocWidget(self.__form_correct.widget,"CorrectTopo","Исправление тологических ошибок",QIcon(),mainwindowAxi)
            addDoc(mainwindowAxi,self.__topo_erorr_doc)
        else:
            isExistDoc=existDocWidget(mainwindowAxi,self.__topo_erorr_doc)
            self.__topo_erorr_doc.setVisible(True)
            self.__topo_erorr_doc.setFocus()
            self.__topo_erorr_doc.raise_()
        #list_topo=[]
        #list_topo.append({"source":"dbвсезоны","result":"dbвсезоны_topoCheck"})
        #list_topo.append({"source":"microregionsTyumen_population","result":"microregionsTyumen_population_topoCheck"})
        self.__form_correct.update(self.__list_topo)
        #if not existDocWidget(mainwindowAxi,self.__topo_erorr_doc):
    def __removeWidget(self):
        if self.__topo_erorr_doc is None:
            return
        DelDocWidget(axipy.app.mainwindow.qt_object(),self.__topo_erorr_doc)
        #DelDocWidget(axipy.app.mainwindow.widget, self.__topo_erorr_doc)
        self.__topo_erorr_doc=None
        self.__form_correct=None





