import axipy
from axipy import Style, Layer

from .ParserMiCommand.addInParsers import getSyleObjects
from .ParserMiCommand.clsLabel import MiLabel
from .ParserMiCommand.clsParser import baseParser
from loguru import logger




def getCustomItems(all_items,start_index):
    count_items=len(all_items)
    custom_labels=[]
    for i in range(start_index,count_items):
        if not(all_items[i]['key'].lower()=="object"):
            break
        custom_labels.append(all_items[i])
    return custom_labels
class AxiLayer:
    def __init__(self,items,source_wor_lines,typeLayer,table):
        self.__items=items
        self.__lines_wor=source_wor_lines
        self.__layer_type=typeLayer
        self.__custom_labels=None
        self.__createLayer(table)
    def __createLayer(self,table):
        global_style=None
        if self.__layer_type=='global':
            ''' слой с единообразным оформлением'''
            wor_string=self.__lines_wor[self.__items[1]['index']].lstrip()
            over_style=getSyleObjects(wor_string)
            '''
            mi_style=wor_string.lstrip("Global")
            if mi_style.lower().find('pen')<mi_style.lower().find('line'):
                mi_style.replace('Line (1,2,0)','')
            global_style=Style.from_mapinfo(mi_style)
            '''
            polygon_style=None
            line_style=None
            point_style=None
            text_style=None
            if over_style['brush'] is not None:
                if over_style['pen'] is not None:
                    polygon_style=Style.from_mapinfo(over_style['brush']+' '+over_style['pen'])
                else:
                    polygon_style = Style.from_mapinfo(over_style['brush']+" Pen (1, 1, 0)")
            if over_style['line'] is not None:
                line_style=Style.from_mapinfo(over_style['line'])
            if over_style['symbol'] is not None:
                point_style=Style.from_mapinfo(over_style['symbol'])
            if over_style['font'] is not None:
                text_style=Style.from_mapinfo(over_style['font'])
            overStyle=axipy.da.CollectionStyle()
            if polygon_style is not None:
                overStyle.for_polygon(polygon_style)
            if line_style is not None:
                overStyle.for_line(line_style)
            if point_style is not None:
                overStyle.for_point(point_style)
            if text_style is not None:
                overStyle.for_text(text_style)
            global_style=overStyle
        if table is None:
            self.__layerAxi=None
            return
        logger.debug("Name Table:"+table.name)
        self.__layerAxi=Layer.create(table)
        if global_style is not None:
            self.__layerAxi.overrideStyle=global_style
        ''' Прозрачность слоя'''
        obj_Alpha=list(filter(lambda item_layer: item_layer['key'].lower() == 'alpha', self.__items))
        if len(obj_Alpha)==1:
            source_Alpha=int(obj_Alpha[0]['words'][1])
            axi_opacity=int(source_Alpha/255*100)
            self.__layerAxi.opacity=axi_opacity
        #from LoadMiWor.ui.processTool.parserWor.clsMiMap import existWordLabel
        #existLabel = existWordLabel(self.__items)
        '''
        Парсим Label
        '''
        label_item=None
        custom_label_item=[]
        for index_key,cur_item in enumerate(self.__items):
            if cur_item['key'].lower() == "selectable":
                isSelectable=False
                if cur_item['words'][1].lower()=='on':
                    isSelectable = True
                try:
                    self.__layerAxi.selectable=isSelectable
                except:
                    pass


            if cur_item['key'].lower()=="label":
                label_item=cur_item
                try:
                    next_item=self.__items[index_key+1]

                    if next_item['key'].lower() == "object":
                        custom_label_item=getCustomItems(self.__items,index_key+1)
                        break
                except:
                    pass


            if cur_item['key'].lower()=="zoom":
                obj_comp=baseParser('zoom ({min_zoom},{max_zoom}) units "{unit}"')
                result=obj_comp.parserToken(self.__lines_wor[cur_item['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'])
                    self.__layerAxi.zoom_restrict=True
                    self.__layerAxi.min_zoom=min_by_unit*unit_zoom.conversion
                    self.__layerAxi.max_zoom=max_by_unit*unit_zoom.conversion
        if label_item is not None:
            MiLabel.createLabelLayer(self.__layerAxi,label_item,self.__lines_wor)
            if len(custom_label_item)>0:
                ''' Пользовательские подписи '''
                self.__custom_labels=MiLabel.createCustomLabelLayer(self.__layerAxi,custom_label_item,self.__lines_wor)

    @property
    def customLabels(self):
        return self.__custom_labels
    @property
    def AxiLayer(self):
        return self.__layerAxi
class MiGroupLayerTab:
    def __init__(self,name):
        self.__name=name
        self.__list_id_layers=[]
        self.__visible=True
        self.__layers=[]
        self.__custom_labels = None
    def setVisible(self,value):
        self.__visible=value
    @property
    def Visible(self):
        return self.__visible
    @property
    def Name(self):
        return self.__name
    def addIdLayers(self,id):
        self.__list_id_layers.append(id)
    def add(self,layer):
        self.__layers.append(layer)
    @property
    def Layers(self):
        return self.__layers
    @property
    def idLayers(self):
        return self.__list_id_layers
    @property
    def count(self):
        return len(self.__layers)

    @property
    def customLabels(self):
        return self.__custom_labels
def prepareGroupLayer(list_tab)->list:
    obj_comp=baseParser('GroupLayer("{name_layer}"')
    out_list=[]
    for item in list_tab:

        obj_group=obj_comp.parserToken(item)
        if obj_group is None:
            if item.find(')')==len(item)-1:
                new_tab=item.replace(')','')
                out_list.append(new_tab)
                out_list.append("end_group_layer")
                continue
            out_list.append(item)
            continue
        name_layer=obj_group.named['name_layer']
        out_list.append(MiGroupLayerTab(name_layer))
    return out_list
