import axipy
from axipy import state_manager, data_manager, selection_manager, Observer, Polygon, MultiPolygon


def selectionIsPolygons():
    retValue=False
    if axipy.gui.selection_manager.count == 0:

        return False
    tab_sel = data_manager.selection
    count_poly=0
    for ft in tab_sel.items():
        if isinstance(ft.geometry,Polygon) or isinstance(ft.geometry,MultiPolygon):
            count_poly=count_poly+1
    if count_poly==0:
        return False
    if count_poly==1:
        return True
    return False
    '''    
    sql = 'Select Count(*) as count  from ' + tab_sel.name + ' Where Str$(obj)="Region" or Str$(obj)="Collection" group by  Str$(obj)'
    tab_is_regions = data_manager.query_hidden(sql)
    if tab_is_regions.count() == 0:
        retValue=False
    else:
        if tab_is_regions.count()==1:
            retValue=True
    tab_is_regions.close()
    '''
    #return retValue
def factoryObserverSelectPolygons(name_observer):
    observer=None
    try:
        observer=state_manager.find(name_observer)
    except:
        pass
    if observer is None:
        observer=state_manager.create(name_observer,False)
        def changeSelection():
            if axipy.gui.selection_manager.count==0:
                observer.setValue(False)
                return
            #tab_sel=axipy.gui.selection_manager.get_as_table()
            tab_sel=axipy.SelectionTable
            sql='Select Count(*) as count  from ' + tab_sel.name + ' Where Str$(obj)="Region" or Str$(obj)="Collection" group by  Str$(obj)'
            tab_is_regions=data_manager.query_hidden(sql)
            count_obj=tab_is_regions.count()
            tab_is_regions.close()
            if count_obj==0:
                observer.setValue(False)
            else:
                if count_obj == 1:
                    observer.setValue(True)
                else:
                    observer.setValue(False)

        setattr(observer, "changeSelection", changeSelection)

        axipy.gui.selection_manager.changed.connect(observer.changeSelection)

        return observer
    return observer
def factoryObserverSelectPolygonsNew(name_observer):
    #observer=axipy.ObserverManager.get(name_observer)
    observer = axipy.observer_manager.get(name_observer)
    if observer is not None:
        return observer

    observer=Observer(name_observer,False)

    def changeSelection():
        count_selection=selection_manager.count
        if count_selection==0:
            observer.value=False
            return
        if count_selection>1:
            observer.value = False
            return
        observer.value=selectionIsPolygons()
        return

    setattr(observer, "changeSelection", changeSelection)

    axipy.gui.selection_manager.changed.connect(observer.changeSelection)
    observer.value=selectionIsPolygons()
    return observer



