#import logging

import axipy
from axipy import Map, CoordSystem, Point, view_manager, Pnt, Feature, Rect
from loguru import logger

from LoadMiWor.ui.processTool.parserWor.ParserMiCommand.addInParsers import getSyleObjects
from LoadMiWor.ui.processTool.parserWor.ParserMiCommand.clsCustomLabel import cloneCustomLabelPropertySetCs
from LoadMiWor.ui.processTool.parserWor.ParserMiCommand.clsGeometry import factoryGeometry, AxiPrepareText
from LoadMiWor.ui.processTool.parserWor.ParserMiCommand.clsParser import baseParser
from LoadMiWor.ui.processTool.parserWor.ParserMiCommand.modParsers.parsersLib import initLoadLibParser
from LoadMiWor.ui.processTool.parserWor.ParserMiCommand.utils import parserWindowInfo, tokenPointPositionToPnt
from LoadMiWor.ui.processTool.parserWor.clsLayer import AxiLayer, prepareGroupLayer, MiGroupLayerTab
from LoadMiWor.ui.processTool.parserWor.clsLegend import MiLegend
from LoadMiWor.ui.processTool.parserWor.clsTables import MiTable
from LoadMiWor.ui.processTool.parserWor.clsTheme import factoryThemeLayer, AxiThemeLayer
from LoadMiWor.ui.processTool.parserWor.parse import parse, search
from LoadMiWor.ui.processTool.utils import tokenPointToPnt, UnitsFromString, calcSizeScreenRect, \
    listStringToString, findLayerByName, getDpi


def existWordLabel(items):

    for i,item in enumerate(items):
        if item['key'].lower()=='label':
            return True,i
    return False,None
def prepareLabelItem(list_item,index_label):
    jkl=0
    if (len(list_item)-1)==index_label:
        return
    if list_item[index_label+1]['key'].lower()=="object":
        return
    children_list=[]
    try:
        children_list=list_item[index_label]['children']
    except:
        pass
    index_del=[]
    for i in range(index_label+1,len(list_item)):
        if list_item[i]['key'].lower()=="object":
            break
        index_del.append(i)
        if len(children_list)>0 and children_list[0]==list_item[i]:
            continue
        children_list.append(list_item[i])
    list_item[index_label]['children']=children_list
    index_del_reverse=list(reversed(index_del))
    for index_del_item in index_del_reverse:
        list_item.pop(index_del_item)


def prepareLineWidthMap(source_line):
    line_source=source_line
    if line_source.find('Min')>=0:
        line_source=line_source.replace("Min","")
    if line_source.find('Max')>=0:
        line_source=line_source.replace("Max","")
    if line_source.find('Restore')>=0:
        line_source=line_source.replace("Restore","")
    if line_source.find('Floating')>=0:
        line_source=line_source.replace("Floating","")
    if line_source.find(' Docked')>=0:
        line_source=line_source.replace(" Docked","")
    return line_source
class MiMapView:
    __scroll=False
    __autoscroll=False
    __snap=False
    def __init__(self,tokenParsers=None):
        if tokenParsers is None:
            return
        self.setProperyWin(tokenParsers)
    def setProperyWin(self,tokenParsers):
        self.__scroll=False
        if tokenParsers.named['scroll_status'].lower()=='on':
            self.__scroll=True
        self.__autoscroll=False
        if tokenParsers.named['autoscroll'].lower()=='on':
            self.__autoscroll=True
        self.__snap=False
        if tokenParsers.named['snap'].lower()=='on':
            self.__snap=True
    @property
    def ScrollBars(self):
        return self.__scroll
    @property
    def Autoscroll(self):
        return self.__autoscroll
    @property
    def Snap(self):
        return self.__snap

def findShade(list_shade,id):
    shade_theme=list(filter(lambda shade: shade['id'] == id, list_shade))
    if shade_theme is None or len(shade_theme)==0:
        return None
    if len(shade_theme)==1:
        return shade_theme[0]
    shade_theme_using=list(filter(lambda shade: shade['isUsing'] == False, shade_theme))
    if shade_theme_using is None or len(shade_theme_using)==0:
        return None
    return shade_theme_using[0]
def findShadeForLayer(list_shade,id):
    shade_start=findShade(list_shade, id)
    if shade_start is None:
        return None
    index_start=shade_start['index']
    shades_for_layer=[]
    shades_for_layer.append(shade_start)
    prev_id_shade=shade_start['id']
    for i in range(index_start+1,len(list_shade)):
        if (list_shade[i]['id']-prev_id_shade)==1:
            shades_for_layer.append(list_shade[i])
        else:
            break
        prev_id_shade=list_shade[i]['id']
    return shades_for_layer
class MiMap:
    __libTokens=initLoadLibParser()
    def __init__(self,item_wor,source_wor,table_wor:MiTable):
        self.__editable_layer=None
        self.__curent_coordSys=None
        self.__layers=[]
        self.__shade_layer=[]
        self.__tables_wor=table_wor
        self.__prepareMap(item_wor,source_wor)
        self.__source_line_wor=source_wor
        self.__title_map=None
        self.__group_layer=None
        self.__legend=[]
        self.__theme_layer_map=[]
    def __prepareMap(self,item_wor,source_wor):
        self.style=None
        self.__line_map=source_wor[item_wor['index']].lstrip().rstrip()
        start_index = 0
        children=item_wor['children']
        if children is not None:
            ''' проверям следующая строка продолжение первой '''
            line_children_1=source_wor[children[0]['index']].lstrip().rstrip()

            if line_children_1[0]==',':
                ''' Да продолжение '''
                self.__line_map=self.__line_map+line_children_1
                start_index=1
        ''' Парсер лист табле для карт '''
        parser_result=self.__libTokens['Map'].parserToken(self.__line_map)
        list_name_table=parser_result.named['names_table']
        self.__list_table_map=list_name_table.split(',')
        self.__list_table_map=prepareGroupLayer(self.__list_table_map)
        width_map_obj=None
        height_obj=None
        position_win_map=None
        for i in range(start_index,len(children)):
            item=children[i]
            if item['key'].lower()=='position':
                self.__line_position=source_wor[item['index']].lstrip().rstrip()
                token_position=parse('Position ({point}) Units "{unit}"',self.__line_position)
               # position_win_map=tokenPointToPnt(token_position.named['point'])
                position_win_map=tokenPointPositionToPnt(token_position.named['point'])
                unit_pos=UnitsFromString(token_position.named['unit'])
                continue
            if item['key'].lower() == 'brush' or item['key'].lower() == 'pen' :
                mi_str=source_wor[item['index']].lstrip().rstrip()
                self.style=getSyleObjects(mi_str)
                continue
            if item['key'].lower()=='width':
                self.__width=source_wor[item['index']]
                self.__width=prepareLineWidthMap(self.__width).strip()
                token_position=parse('Width {width} Units "{w_unit}" Height {height} Units "{h_unit}"',self.__width)
                obj_width=token_position.named['width']
                obj_height=token_position.named['height']
                width_val=parserWindowInfo(obj_width)
                height_val=parserWindowInfo(obj_height)
                height_obj = {"value": height_val, "unit": token_position.named['h_unit']}
                width_map_obj = {"value": width_val,"unit": token_position.named['w_unit']}
                '''
                dpi=None
                size_main_window=None
                if obj_width.isnumeric():
                    width_map_obj={"value":float(token_position.named['width']),"unit":token_position.named['w_unit']}
                else:
                    dpi=getDpi()
                    size_main_window=axipy.mainwindow.qt_object().geometry()
                    width_map=size_main_window.width()/dpi
                    width_map_obj = {"value": width_map,
                                     "unit": token_position.named['w_unit']}
                if obj_height.isnumeric():
                    height_obj={"value":float(token_position.named['height']),"unit":token_position.named['h_unit']}
                else:
                    if dpi is None:
                        dpi = getDpi()
                        size_main_window = axipy.mainwindow.qt_object().geometry()
                    height_map=size_main_window.height()/dpi
                    height_obj = {"value": height_map,
                                      "unit": token_position.named['h_unit']}
                '''
                continue
        self.__rect_map_view=calcSizeScreenRect(position_win_map,unit_pos,width_map_obj,height_obj)

        possition_obj= {'position':position_win_map,'unit':unit_pos}
        size_map_position={'width':width_map_obj,'height':height_obj}
        self.position_object=Rect(possition_obj['position'].x,possition_obj['position'].y,possition_obj['position'].x+width_map_obj['value'],possition_obj['position'].y+height_obj['value'])
        return
    def setMapWinProperty(self,item):
        ''' Установка свойств окна карты '''
        mi_cmd=listStringToString(item['words'])
        parser_result=self.__libTokens['Set Window'].parserToken(mi_cmd)
        if parser_result is not None:
            self.__miMapView=MiMapView(parser_result)
            return
        mi_cmd=self.__source_line_wor[item["index"]]
        token_title=search('Set Window FrontWindow() Title "{title_map}"',mi_cmd+" ")
        if token_title is not None:
            ''' становка заголовка карты '''
            self.__title_map=token_title.named['title_map']
            self.__mapview.title=self.__title_map

    @property
    def indexEditableLayer(self):
        return self.__editable_layer
    def setMap(self,item):
        if item['children']==None:
            if item['words'][2].lower()=='layer':
                ''' Установка редактируемого слоя '''
                self.__editable_layer=int(item['words'][3])
            return
        children_item=item['children']
        if children_item[0]['key'].lower()=='layer' or children_item[0]['key'].lower()=='grouplayer':
            ''' Слои карты '''
            self.__createLayersAndGroup(children_item)
            pass
        if children_item[0]['key'].lower()=='coordsys' or children_item[0]['key'].lower()=='image':
            ''' Картографические свойства карты'''
            for item_map in children_item:
                mi_command=self.__source_line_wor[item_map['index']].lstrip()
                if item_map['key'].lower()=='coordsys':

                    self.__map_coordsys= CoordSystem.from_prj(mi_command)
                    continue
                if item_map['key'].lower()=='center':
                    token_center=parse("Center ({point})",mi_command)
                    pts=token_center.named['point'].split(",")
                    self.__center_map=Point(float(pts[0]),float(pts[1]),cs=self.__map_coordsys)
                    continue
                if item_map['key'].lower()=='zoom':
                    token_zoom=parse('Zoom {zoom} Units "{mi_units}"',mi_command)
                    self.__zoom_value=float(token_zoom.named['zoom'])
                    zoom_unit=token_zoom.named['mi_units']
                    self.__zoom_unit=UnitsFromString(zoom_unit)
                    continue
                if item_map['key'].lower()=='distance':
                    token_units=parse('Distance Units "{distance}" Area Units "{area}" XY Units "{xy}"',mi_command)
                    if token_units is None:
                        print("Erorr parser :"+mi_command)
                        return
                    self.__distance_unit=UnitsFromString(token_units.named['distance'])
                    self.__area_unit=UnitsFromString(token_units.named['area'])
                    xy_str=token_units.named['xy']
                    if xy_str=='degree':
                        self.__xy_unit=None
                    else:
                        self.__xy_unit=    UnitsFromString(xy_str)
                    continue



            pass
    def setCurentCoordSystem(self,mi_cmd):
        mi_token=parse("Set {mi_coordsys}",mi_cmd)
        self.__curent_coordSys=CoordSystem.from_prj(mi_token.named['mi_coordsys'])
    def addTheme(self,item):
        shade_layer=factoryThemeLayer(item,self.__source_line_wor)
        shade_layer['isUsing']=False
        shade_layer['index']=len(self.__shade_layer)
        if shade_layer is not None:
            self.__shade_layer.append(shade_layer)
    def createObj(self,item):
        ''' Создание геометрических объектов '''
        name_object=item['words'][1].lower()
        try:
            axi_geo_obj=factoryGeometry(name_object,item['index'],self.__source_line_wor,self.__curent_coordSys)
        except :
            axi_geo_obj=None
        if axi_geo_obj is None:
            print("Erorr Parse Object "+name_object)
            return

        layer_cosmetic=self.__map_axi.cosmetic
        #tab_cosmetic=self.__map_axi.cosmetic.data_object
        tab_cosmetic =layer_cosmetic.data_object
        #cosmetic_schema=tab_cosmetic.schema
        if isinstance(axi_geo_obj,AxiPrepareText):
            feature = Feature({}, geometry=axi_geo_obj.createAxiTextGeoObject(self.AxiMapView), style=axi_geo_obj.style)
        else:
            feature = Feature({}, geometry=axi_geo_obj.geometry, style=axi_geo_obj.style)
        tab_cosmetic.insert([feature])

    def addLegend(self,legend:MiLegend):
        self.__legend.append(legend)
    @property
    def Legends(self):
        return self.__legend
    @property
    def map(self):
        return self.__map_axi
    @property
    def AxiMapView(self):
        return self.__mapview
    def __prepareLayerThemeNew(self,layerAxi,layer_theme,id_layer):
        ''' Добавляем к основному картографическому слою тематические'''
        list_theme_for_layers=[]
        ''' Ищем  тематики для векторного слоя с id '''
        shades_layer=findShadeForLayer(self.__shade_layer,id_layer)
        if shades_layer is None:
            return None
        try:
            if not (len(shades_layer)==len(layer_theme)):
                logger.error("Что то пошло не так число тематических слоев не равно числу тематик ")
                return None
        except:
            return None
        layer_theme.reverse()
        for i in range(len(layer_theme)):
            theme=layer_theme[i]
            shade_theme=shades_layer[i]
            if shade_theme is None:
                continue

            self.__shade_layer[shade_theme['index']]['isUsing']=True
            curentAxiThematic=shade_theme['shade']
            axiTheme=curentAxiThematic.themeLayer

            if theme.zoom_visible:
                axiTheme.zoom_restrict=True
                axiTheme.min_zoom=theme.min_zoom
                axiTheme.max_zoom=theme.max_zoom
            layerAxi.thematic.add(axiTheme)
            if layerAxi.thematic.count>1:
                layerAxi.thematic.move(layerAxi.thematic.count-1, 0)
            curentAxiThematic.update()
            if not theme.visible:
                axiTheme.visible=False
            list_theme_for_layers.append({'id':theme.Id,'theme':axiTheme,'id_vector':id_layer})
        theme_layers=layerAxi.thematic
        return list_theme_for_layers
    def __prepareLayerTheme(self,layerAxi,layer_theme):
        ''' Добавляем к основному картографическому слою тематические'''
        list_theme_for_layers=[]
        for theme in layer_theme:
            id=theme.Id
            #shade_theme=list(filter(lambda shade: shade['id'] == id, self.__shade_layer))
            shade_theme=findShade(self.__shade_layer,id)
            if shade_theme is None or len(shade_theme)==0:
                continue
            curentAxiThematic=shade_theme[0]['shade']
            axiTheme=curentAxiThematic.themeLayer
            if theme.zoom_visible:
                axiTheme.zoom_restrict=True
                axiTheme.min_zoom=theme.min_zoom
                axiTheme.max_zoom=theme.max_zoom
            layerAxi.thematic.add(axiTheme)
            curentAxiThematic.update()
            list_theme_for_layers.append({'id':id,'theme':axiTheme})
        return list_theme_for_layers
    @property
    def ThemeLayers(self):
        return self.__theme_layer_map
    def __createLayers(self,items_layer_wor):
        ''' Парсим список слоев карты'''
        index_table=0
        list_layer=[]
        theme_layer=[]
        active_group_layer=None
        for mi_layer in items_layer_wor:
            if mi_layer['key'].lower()=='grouplayer':
                if active_group_layer is not None:
                    self.__group_layer.append(active_group_layer)
                    active_group_layer=None
                id_layer=int(mi_layer['words'][1])
                visible=mi_layer['children'][0]['words'][1].lower()
                b_visible=True
                if visible=='off':
                    b_visible=False
                self.__group_layer[id_layer-1].setVisible(b_visible)
                continue
            str_id_layer=mi_layer['words'][1]
            if mi_layer['children'][0]['key'].lower()=='display':
                type_layer_view= mi_layer['children'][0]['words'][1].lower()
                existLabelKey,index_label=existWordLabel(mi_layer['children'])
                if existLabelKey:
                    prepareLabelItem(mi_layer['children'],index_label)
                if type_layer_view=='global' or  type_layer_view=='graphic' or type_layer_view=='off':
                    ''' базовый слой '''
                    name_table=self.__list_table_map[index_table]
                    if name_table=='end_group_layer':
                        index_table=index_table+1
                        '''
                        if index_table>=len(self.__list_table_map):
                            self.__group_layer.append(active_group_layer)
                            active_group_layer=None
                            continue
                        '''
                        name_table=self.__list_table_map[index_table]
                        self.__group_layer.append(active_group_layer)
                        active_group_layer=None
                    if isinstance(name_table,MiGroupLayerTab):
                        miGroupLayer=self.__list_table_map[index_table]
                        index_table=index_table+1

                        name_table=self.__list_table_map[index_table]
                        if self.__group_layer is None:
                            self.__group_layer=[]
                        active_group_layer=miGroupLayer

                    table_curent=self.__tables_wor.getByName(name_table)
                    axi_layer=AxiLayer(mi_layer['children'],self.__source_line_wor,type_layer_view,table_curent)
                    if type_layer_view=='off':
                        axi_layer.AxiLayer.visible=False
                    index_table=index_table+1
                    list_layer.append(axi_layer)
                    if active_group_layer is not None:
                        active_group_layer.addIdLayers(len(list_layer)-1)
                    if len(theme_layer)>0:
                        ''' Для данного слоя существуют тематические'''
                        self.__prepareLayerTheme(axi_layer.AxiLayer,theme_layer)
                        theme_layer.clear()
                    continue
                else:
                    if type_layer_view=='value':
                        ''' Тематический слой '''
                        theme_layer.append(AxiThemeLayer(int(str_id_layer)))


        if len(list_layer)==0:
            return
        list_layer_axi=[]
        for layer in list_layer:
            try:
                list_layer_axi.append(layer.AxiLayer)
            except Exception as ex:
                jkl=0
        self.__map_axi=Map(list_layer_axi)
        ''' Прверяем есть ли группы слоев '''
        if self.__group_layer is not None and len(self.__group_layer)>0:
            ''' Создаем группы слоев'''
            layers=self.__map_axi.layers
            for group in self.__group_layer:
                name=group.Name
                list_index=group.idLayers
                self.__map_axi.layers.group(list_index,name)
                new_layer_group=findLayerByName(self.__map_axi,name)
                if new_layer_group is None:
                    continue
                new_layer_group.visible=group.Visible


        #self.__map_axi.rect=self.__rect_map_view
        self.__map_axi.areaUnit=self.__area_unit
        self.__map_axi.distanceUnit=self.__distance_unit
        for layer in list_layer:
            custom_label=layer.customLabels
            if custom_label is None or len(custom_label)==0:
                continue
            for cst_label in custom_label:
                self.__map_axi.custom_labels.set(layer.AxiLayer, cst_label['id'], cst_label['cst_label'])
        self.__mapview = view_manager.create_mapview(self.__map_axi)
        self.__mapview.rect=self.__rect_map_view
        self.__mapview.coordsystem=self.__map_coordsys
        self.__mapview.center=Pnt(self.__center_map.x,self.__center_map.y)
        #self.__mapview.set_zoom(self.__zoom_value,self.__zoom_unit)
        self.__mapview.set_zoom_and_center(self.__zoom_value,self.__mapview.center,self.__zoom_unit)



        return

    def __createLayersAndGroup(self,items_layer_wor):
        ''' Парсим список слоев карты'''
        index_table=0
        list_layer=[]
        self.__theme_layer=[]
        active_group_layer=None

        if items_layer_wor[0]['key'].lower()=='layer' and items_layer_wor[0]['children'] is None:
            '''
            Что то не так с деревом
            
            '''
            if items_layer_wor[1]['key'].lower() == 'display':
                items_layer_wor[0]['children']=[items_layer_wor[1]]

        for mi_layer in items_layer_wor:
            if mi_layer['key'].lower()=='grouplayer':
                if active_group_layer is not None:
                    self.__group_layer.append(active_group_layer)
                    list_layer.append(active_group_layer)
                    active_group_layer=None
                id_layer=int(mi_layer['words'][1])
                visible=mi_layer['children'][0]['words'][1].lower()
                b_visible=True
                if visible=='off':
                    b_visible=False
                self.__group_layer[id_layer-1].setVisible(b_visible)
                continue
            str_id_layer=mi_layer['words'][1]
            try:
                if mi_layer['children'] is None:
                    continue
            except:
                continue
            logger.debug("Layer "+str_id_layer)
            if mi_layer['children'][0]['key'].lower()=='display':
                type_layer_view= mi_layer['children'][0]['words'][1].lower()
                existLabel,index_label=existWordLabel(mi_layer['children'])
                if existLabel:
                    prepareLabelItem(mi_layer['children'],index_label)
                if (type_layer_view=='global' or  type_layer_view=='graphic' or type_layer_view=='off') or existLabel:
                    ''' базовый слой '''
                    #print("Index tab "+str(index_table)+" all tab="+str(len(self.__list_table_map)))
                    if index_table>=(len(self.__list_table_map)):
                        continue
                    name_table=self.__list_table_map[index_table]
                    if isinstance(name_table,str):
                        name_table=name_table.strip()
                    if name_table=='end_group_layer':
                        index_table=index_table+1
                        '''
                        if index_table>=len(self.__list_table_map):
                            self.__group_layer.append(active_group_layer)
                            active_group_layer=None
                            continue
                        '''
                        name_table=self.__list_table_map[index_table]
                        self.__group_layer.append(active_group_layer)
                        list_layer.append(active_group_layer)
                        active_group_layer=None
                    if isinstance(name_table,MiGroupLayerTab):
                        miGroupLayer=self.__list_table_map[index_table]
                        index_table=index_table+1

                        name_table=self.__list_table_map[index_table]
                        if self.__group_layer is None:
                            self.__group_layer=[]
                        active_group_layer=miGroupLayer

                    table_curent=self.__tables_wor.getByName(name_table)
                    axi_layer=AxiLayer(mi_layer['children'],self.__source_line_wor,type_layer_view,table_curent)
                    if type_layer_view=='off':
                        if axi_layer.AxiLayer is not None:
                            axi_layer.AxiLayer.visible=False
                    index_table=index_table+1
                    if active_group_layer is not None:
                        active_group_layer.add(axi_layer)
                    else:
                        list_layer.append(axi_layer)

                    if len(self.__theme_layer)>0:
                        logger.debug("Thematic Layer")
                        ''' Для данного слоя существуют тематические'''
                        count_vector_layer=len(list_layer)
                        if self.__group_layer is not None:
                            for group in self.__group_layer:
                                count_vector_layer=group.count
                        if active_group_layer is not None:
                            count_vector_layer= count_vector_layer+active_group_layer.count
                        themes_layres=self.__prepareLayerThemeNew(axi_layer.AxiLayer,self.__theme_layer,count_vector_layer)
                        if themes_layres is None:
                            self.__theme_layer.clear()
                            #self.__theme_layer_map=None
                            continue
                        if self.__theme_layer_map is None:
                            self.__theme_layer_map=[]
                        ''' Добавляем с порядковым номером теамтики в слое'''
                        for i,tm_layer in enumerate(themes_layres):
                            tm_layer['thema_id']=i
                            self.__theme_layer_map.append(tm_layer)
                        #self.__theme_layer_map.extend(themes_layres)
                        #self.__theme_layer_map=themes_layres
                        self.__theme_layer.clear()
                    jkl=0
                    continue
                else:

                    if type_layer_view=='value' or (not existLabel):
                        if type_layer_view!='graphic' :
                            ''' Тематический слой '''
                            zoom_visible=False
                            theme_min_zoom=None
                            theme_max_zoom=None
                            for item_theme in mi_layer['children']:
                                if item_theme['key'].lower()=='zoom':

                                    obj_comp=baseParser('zoom ({min_zoom},{max_zoom}) units "{unit}"')
                                    #mi_wor_line=self.__source_line_wor[item_theme['index']]
                                    result=obj_comp.parserToken(self.__source_line_wor[item_theme['index']].strip().lower())
                                    if result is not None:
                                        unit_zoom=axipy.cs.LinearUnit.by_name(result['unit'])
                                        min_by_unit=float(result['min_zoom'])
                                        max_by_unit=float(result['max_zoom'])
                                        zoom_visible=True
                                        theme_min_zoom=min_by_unit*unit_zoom.conversion
                                        theme_max_zoom=max_by_unit*unit_zoom.conversion
                            axiTheme=AxiThemeLayer(int(str_id_layer),zoom_visible,theme_min_zoom,theme_max_zoom)
                            if type_layer_view=='off':
                                axiTheme.visible=False
                            else:
                                axiTheme.visible = True
                            self.__theme_layer.append(axiTheme)

                jkl=0
        if len(list_layer)==0:
            return

        self.__map_axi=Map()
        for layer in list_layer:
            if isinstance(layer,AxiLayer) and layer.AxiLayer is not None:
                self.__map_axi.layers.append(layer.AxiLayer)
                try:
                    arrow_style_label=layer.AxiLayer.arrow_style
                    if arrow_style_label is not None:
                        self.__map_axi.custom_labels.set_default_arrow_type(arrow_style_label)
                except:
                    pass
                continue
            ''' Прверяем есть ли группы слоев '''
            layers_from_group=layer.Layers
            name=layer.Name
            self.__map_axi.layers.add_group(name)
            self.__map_axi.layers.move(0,self.__map_axi.layers.count-1)
            map_temp=self.__map_axi
            layer_group=self.__map_axi.layers.at(self.__map_axi.layers.count-1)
            for gr_layer in layers_from_group:
                layer_group.append(gr_layer.AxiLayer)
            layer_group.visible=layer.Visible

        for layer in list_layer:
            custom_label=layer.customLabels
            if custom_label is None or len(custom_label)==0:
                continue
            for cst_label in custom_label:
                '''
                point_cs_map=Point(cst_label['cst_label'].position.x,cst_label['cst_label'].position.y,self.__map_coordsys)
                cst_label_desc=cst_label['cst_label']
                cst_label_desc.position=point_cs_map
                #cst_label['cst_label'].position.coorfsystem=self.__map_coordsys
                '''
                new_propert=cloneCustomLabelPropertySetCs(cst_label['cst_label'],self.__map_coordsys)
                self.__map_axi.custom_labels.set(layer.AxiLayer, cst_label['id'], new_propert)
        #self.__map_axi.rect=self.__rect_map_view
        self.__map_axi.areaUnit=self.__area_unit
        self.__map_axi.distanceUnit=self.__distance_unit
        self.__mapview = view_manager.create_mapview(self.__map_axi)
        self.__mapview.rect=self.__rect_map_view
        self.__mapview.coordsystem=self.__map_coordsys
        self.__mapview.center=Pnt(self.__center_map.x,self.__center_map.y)
        #self.__mapview.set_zoom(self.__zoom_value,self.__zoom_unit)
        self.__mapview.set_zoom_and_center(self.__zoom_value,self.__mapview.center,self.__zoom_unit)


        return




