import axipy
from axipy import LabelOverlap, Style, CustomLabelProperties, Point, LabelLinePosition

from LoadMiWor.ui.processTool.parserWor import parse
from LoadMiWor.ui.processTool.parserWor.ParserMiCommand.clsCustomLabel import factoryCustomLabel
from LoadMiWor.ui.processTool.parserWor.ParserMiCommand.clsParser import baseParser
from LoadMiWor.ui.processTool.parserWor.ParserMiCommand.utils import StringToBoolean, setLabelFont, setPosition, \
    SetOffsetLabel, getStyleLineLabel
from LoadMiWor.ui.processTool.parserWor.parse import search


class MiLabel:
    def __init__(self,item_label):

        self.__label_item=item_label

    @staticmethod
    def createLabelLayer(layer,items,wor_lines):
        '''
        Формирование подписей слоя ( Label)
        :param layer:
        :param items:
        :param wor_lines:
        :return:
        В AxiPy пока реализованы не все возможности
        '''
        property_default_label={}
        token_Auto=None
        if items is None:
            return
        mi_str=wor_lines[items['index']].lower().strip()
        '''Auto Retry'''
        token_auto_retry=search("auto retry {on_off} ",mi_str)
        if token_auto_retry is not None:
            layer.label.useClip=StringToBoolean(token_auto_retry['on_off'])

        token_font=search('font ({params})',mi_str)
        if token_font is not None:
            str_mi_font=token_font['params']

            setLabelFont(layer.label,str_mi_font)
        token_position=search("position {type} ",mi_str)
        if token_position is not None:
            add_param_position=None
            if token_position['type']=='above'or token_position['type']=='below':
                add_token=search("position "+token_position['type']+" {add_pos} ",mi_str)
                if add_token is not None:
                    add_param_position=add_token['add_pos']
                    if not (add_param_position=='left' or add_param_position=='right'):
                        add_param_position=None
            param_pos=token_position['type']
            if add_param_position is not None:
                param_pos=param_pos+"_"+add_param_position
            new_Layout=setPosition(layer.label.pointLayout,param_pos)
            mi_str = wor_lines[items['index']].lower().strip()
            arrow_style=getStyleLineLabel(mi_str)
            layer.arrow_style=arrow_style
            if new_Layout is not None:
                layer.label.pointLayout=   new_Layout
            new_Layout_line=setPosition(layer.label.lineLayout,param_pos)
            if new_Layout_line is not None:
                layer.label.lineLayout=new_Layout_line

            new_LayoutArea=setPosition(layer.label.areaLayout,param_pos)
            if new_LayoutArea is not None:
                layer.label.areaLayout=new_LayoutArea

        for item in items['children']:
            mi_cmd=wor_lines[item['index']]
            if item['key'].lower()=='with':
                ''' Выражение из которого извлекается текст'''
                #token_exp=search("With {expre} ", mi_cmd+" ")
                token_exp=parse.parse('With {expre}',mi_cmd.lstrip())
            token_Auto = search("Auto {on_off} ", mi_cmd)
            if token_Auto is not None:
                if token_Auto.named['on_off'] == 'On':
                    layer.label.visible = True
            if item['key'].lower()=='parallel' or item['key'].lower()=='follow':
                if item['key'].lower() == 'parallel':
                    layer.label.linePosition=LabelLinePosition.Parallel
                if item['key'].lower()=='follow':
                    layer.label.linePosition = LabelLinePosition.FollowPath
                token_Overlap=search("Overlap {on_off} ",mi_cmd)
                if token_Overlap['on_off'].lower()=='on':
                    layer.label.placementPolicy=LabelOverlap.AllowOverlap
                else:
                    layer.label.placementPolicy=LabelOverlap.DisallowOverlap

                token_AutoReplay=search("Auto Retry {on_off} ",mi_cmd)
                token_offset=search("Offset {offset}",mi_cmd)
                if token_offset is not None:
                    offset=int(token_offset['offset'])
                    SetOffsetLabel(layer,offset)
            if item['key'].lower()=='visibility':
                ''' Параметры видимости Label'''

                if item['words'][1].lower()=='zoom':
                    ''' Устанавливается дипозон видимости'''
                    obj_comp=baseParser('visibility zoom ({min_zoom},{max_zoom}) units "{unit}"')
                    result=obj_comp.parserToken(wor_lines[item['index']].strip().lower())
                    if result is not None:
                        layer.label.rangeEnabled=True
                        unit_zoom=axipy.cs.LinearUnit.by_name(result['unit'])
                        min_by_unit=float(result['min_zoom'])
                        max_by_unit=float(result['max_zoom'])
                        layer.label.rangeMin=min_by_unit*unit_zoom.conversion
                        layer.label.rangeMax=max_by_unit*unit_zoom.conversion

        if token_exp is not None:
            layer.label.text=token_exp.named['expre']
            '''
            layer.label.visible = False
            
            if token_Auto is not None:
                if token_Auto.named['on_off']=='On':
                    layer.label.visible = True
            '''
    @staticmethod
    def createCustomLabelLayer(layer,items,wor_lines):
        labels=[]
        for custom_item in items:
            line_wor=wor_lines[custom_item['index']].strip()
            cls_axiCustomLabel=factoryCustomLabel(line_wor+" ")
            '''
            result = parse.parse('Object {id} Anchor ({coords})', line_wor)
            if result is None:
                continue
            id_ft=int(result.named['id'])
            str_xy=result.named['coords']
            sxy=str_xy.split(",")
            x=float(sxy[0])
            y=float(sxy[1])
            cst_label = CustomLabelProperties()
            cst_label.position = Point(x, y)
            '''
            labels.append({'id':cls_axiCustomLabel.id,"cst_label":cls_axiCustomLabel.customLabelProperties})
        return labels




        