from axipy import view_manager, Legend, Map, Layer

from LoadMiWor.ui.processTool.parserWor.clsMiMap import MiMap, prepareLineWidthMap
from LoadMiWor.ui.processTool.parserWor.parse import search, parse
from LoadMiWor.ui.processTool.utils import tokenPointToPnt, UnitsFromString, calcSizeScreenRect

def clearLegendView(legende_view):
    count=len(legende_view.legends)
    for j in range(count):
        legende_view.legends.remove(0)
def FindVectorLayer(map_curent:Map,id_layer):
    layers=map_curent.layers
    index_layer=0
    for layer in layers:
        if isinstance(layer, Layer):
            index_layer=index_layer+1
            if index_layer==id_layer:
                ''' Нашли векторный слой '''
                return layer
        else:
            ''' GroupLayer'''
            group_layer=layer
            for layer in group_layer:
                index_layer = index_layer + 1
                if index_layer==id_layer:
                    ''' Нашли векторный слой '''
                    return layer
    return None


class LegendeView:
    def create(self,item,wor_source,mi_map:MiMap):

        self.__rect_win=None
        self.__id_layer=[]
        self.__parserLegendeView(item,wor_source)
        temp_legends=[]
        for legend in mi_map.Legends:
            leg_id=legend.IdLayer
            legends=list(filter(lambda leg: leg == leg_id, self.__id_layer))
            if legends is None or len(legends)==0:
                continue
            themes_layer=list(filter(lambda theme: theme['id'] == legends[0], mi_map.ThemeLayers))
            temp_legends.append(themes_layer[0])
        if len(temp_legends)>0:
            ''' Группируем тематики по слоям'''
            layers_theme=[]
            for leg_item in temp_legends:
                layer_thema_exist=list(filter(lambda theme: theme['layer_id'] == leg_item['id_vector'],  layers_theme))
                if len(layer_thema_exist)==0:
                    ''' слоя еще нет'''
                    layers_theme.append({'layer_id':leg_item['id_vector'],'themas':[leg_item]})

                else:
                    layer_thema_exist[0]['themas'].append(leg_item)
            ''' Формируем окно легенды'''
            legendView = view_manager.create_legendview(mi_map.AxiMapView)
            legendView.position=self.__rect_map_view
            clearLegendView(legendView)
            for leg_item in  layers_theme:

                layer=FindVectorLayer(mi_map.AxiMapView.map,leg_item['layer_id'])
                for theme in leg_item['themas']:
                    cur_theme=layer.thematic.at(theme['thema_id'])
                    legend = Legend(cur_theme)
                    legendView.legends.append(legend)
                #legend = Legend(leg_item['theme'])
                #legendView.legends.append(legend)
            legendView.arrange()

    def __parserLegendeView(self,item_base,wor_source):
        items=item_base['children']
        position_win_map=None
        unit_pos=None
        width_map_obj=None
        height_obj=None
        for item in items:
            mi_str=wor_source[item['index']].lstrip()+" "
            mi_str_low=mi_str.lower()
            if item['key'].lower()=='position':
                token_position=parse('position ({point}) units "{unit}" ',mi_str_low)
                if token_position is not None:
                    position_win_map=tokenPointToPnt(token_position.named['point'])
                    unit_pos=UnitsFromString(token_position.named['unit'])
                    continue
            if item['key'].lower()=='width':

                self.__width=prepareLineWidthMap(mi_str).strip()
                token_position=parse('Width {width} Units "{w_unit}" Height {height} Units "{h_unit}"',self.__width)
                width_map_obj={"value":float(token_position.named['width']),"unit":token_position.named['w_unit']}
                height_obj={"value":float(token_position.named['height']),"unit":token_position.named['h_unit']}
                continue
            if item['key'].lower()=='frame':
                token_layer=parse('frame from layer {id_layer} ',mi_str_low)
                self.__id_layer.append(int(token_layer.named['id_layer']))
                continue

        self.__rect_map_view=calcSizeScreenRect(position_win_map,unit_pos,width_map_obj,height_obj)
        return

        