import axipy
from axipy import Rect, Style, MapReportItem, MapView, TableView, TableReportItem, LegendView, LegendReportItem
from loguru import logger

from LoadMiWor.ui.DlgMessageSelectView import DlgSelectView
from LoadMiWor.ui.processTool.parserWor.parse import search
from LoadMiWor.ui.processTool.utils import tokenPointToPnt


def compareTitleMap(axi_title,mapinfo_title):
    ''' Сравнение заголовков карт Axioma и MapInfo'''
    axi_new_title=axi_title
    if axi_title.find("Карта:")>=0:
        axi_new_title=axi_title.replace("Карта:","")
    new_mapinfo_title=mapinfo_title
    if mapinfo_title.find(" Карта")>=0:
        new_mapinfo_title=mapinfo_title.replace(" Карта","")
    if axi_new_title.strip()==new_mapinfo_title.strip():
        return True
    axi_new_title=axi_new_title.strip()
    list_item_mi=mapinfo_title.split(',')
    if len(list_item_mi)==0:
        return False
    items_axi_title=axi_new_title.split(",")
    i3=len(items_axi_title)-1
    if len(list_item_mi)==1:
        if i3>1:
            return False
        if list_item_mi[0].find("Карта")>0:
            list_item_mi[0]=list_item_mi[0].replace(" Карта","")
        if list_item_mi[0]==items_axi_title[0]:
            return True
        return False
    isReduction=False
    if list_item_mi[1]=='...':
        ''' Заголовок с сокращением'''
        isReduction=True
    i2=len(list_item_mi)-1
    if list_item_mi[i2].find("Карта")>0:
        list_item_mi[i2]=list_item_mi[i2].replace(" Карта","")
        list_item_mi[i2]=list_item_mi[i2].strip()

    if isReduction:
        ''' Сокращенное название карты в MapInfo '''

        len_name_mi_0=len(list_item_mi[0])
        len_name_mi_end=len(list_item_mi[i2])
        item_title_axi_start=items_axi_title[0]
        item_title_axi_end=items_axi_title[i3]
        ''' Для MapInfo максимальная длина имени 31 символ '''
        if len_name_mi_0>=31:
            item_title_axi_start=items_axi_title[0][0:31]
        if len_name_mi_end>=31:
            item_title_axi_end=items_axi_title[i3][0:31]


        #if list_item_mi[0]==items_axi_title[0] and list_item_mi[i2]==items_axi_title[i3]:
        if list_item_mi[0]==item_title_axi_start and list_item_mi[i2]==item_title_axi_end:
            return True
    return False
def getObjectByTitleFrame(title_frame):
    obj_items=title_frame.split(' ')
    if obj_items[1]=='Карта' or obj_items[1]=='Map':
        ''' это карта'''
        for map_view in axipy.gui.view_manager.mapviews:
            cur_map_title=map_view.title
            isOk=compareTitleMap(cur_map_title,title_frame)
            if isOk :
                return map_view
    else:
        if obj_items[1].find('Список')>=0 or obj_items[1]=='List':
            ''' Это таблица списком'''
            name_table=obj_items[0]
            id_tab=0
            if name_table.find(':')>=0:
                temp_list=name_table.split(':')
                id_tab=int(temp_list[1])
                name_table=temp_list[0]
            ''' Формируем имя объекта в терминах Axioma'''
            name_axi='Список: '+name_table
            if id_tab>1:
                name_axi=name_axi+" ("+str(id_tab+1)+")"
            for tab_view in  axipy.gui.view_manager.tableviews:
                title_view=tab_view.title
                if title_view==name_axi:
                    return tab_view
    return None
def parserFrame(lines_mi):
    rect_frame=None
    style_border=None
    style_fill=None
    map_title=None
    isFillOn=False
    for line in lines_mi:
        token_item=search("Create Frame ({ld}) ({ur})",line.lstrip()+" ")
        if token_item is not None:
            pnt_left_down=tokenPointToPnt(token_item.named['ld'])
            pnt_rightUp=tokenPointToPnt(token_item.named['ur'])
            rect_frame=Rect(pnt_left_down.x,pnt_left_down.y,pnt_rightUp.x,pnt_rightUp.y)
            continue
        token_item=search("Pen ({style_pen})",line.lstrip()+" ")
        if token_item is not None:
            style_border=Style.from_mapinfo(line.lstrip())
            continue
        token_item=search("Brush ({style_brush})",line.lstrip()+" ")
        if token_item is not None:
            style_fill=Style.from_mapinfo(line.lstrip())
            continue
        token_item=search('Title "{title_map}"',line.lstrip()+" ")
        if token_item is not None:
            map_title=token_item.named['title_map']
            continue
        isFillOnParser=search('FillFrame {fill_on}',line.lstrip()+" ")
        if isFillOnParser is not None:
            ''' как заполнять frame картой'''
            isFillOn=False
            if line.lstrip().lower().find("on")>0:
                isFillOn=True
        ''' ищем карту с названием'''
        active_map=None
        active_mapview=None
        objItemReport=None
        '''
        for map_view in axipy.gui.view_manager.mapviews:
            cur_map_title=map_view.title
            isOk=compareTitleMap(cur_map_title,map_title)
            #if map_title==cur_map_title:
            if isOk:
                active_map=map_view.map
                active_mapview=map_view
                break
        '''
        active_object_frame=getObjectByTitleFrame(map_title)
        if active_object_frame is None:
            logger.debug("Not found Franme Title:"+map_title)
            #print("Not found Franme Title:"+map_title)
            clsDlg=DlgSelectView(axipy.app.mainwindow.qt_object())
            #clsDlg.show(map_title)
            clsDlg.exec_(map_title)
            active_object_frame=clsDlg.selectView

        if active_object_frame is not None:
            if isinstance(active_object_frame,MapView):

                objItemReport=MapReportItem(rect_frame,active_object_frame.map)
                objItemReport.scale=active_object_frame.scale
                objItemReport.center=active_object_frame.center
                if isFillOn :
                    objItemReport.show_all()
            if isinstance(active_object_frame,TableView):
                objItemReport=TableReportItem(rect_frame,active_object_frame.data_object)
            if isinstance(active_object_frame,LegendView):
                objItemReport=LegendReportItem(rect_frame,active_object_frame.legends[0])
            if objItemReport is not None:
                objItemReport.border_style=style_border

            '''
            if isFillOn:
                mapItemReport.show_all()
            else:
                mapItemReport.scale=active_mapview.scale
            '''


        #mapItemReport.zoom=

        return objItemReport
def parserFrameAlter(source,index_start):
    index=index_start
    mi_create_frame=source[index]
    rect_frame = None
    style_border = None
    style_fill = None
    map_title = None
    isFillOn = False
    token_item=search("Create Frame ({ld}) ({ur})", mi_create_frame.lstrip() + " ")
    if token_item is None:
        return None
    pnt_left_down = tokenPointToPnt(token_item.named['ld'])
    pnt_rightUp = tokenPointToPnt(token_item.named['ur'])
    rect_frame = Rect(pnt_left_down.x, pnt_left_down.y, pnt_rightUp.x, pnt_rightUp.y)
    index=index+1
    line=source[index]
    token_item = search("Pen ({style_pen})", line.lstrip() + " ")
    if token_item is not None:
        style_border = Style.from_mapinfo(line.lstrip())
    index = index + 1
    line = source[index]
    token_item = search("Brush ({style_brush})", line.lstrip() + " ")
    if token_item is not None:
        style_fill = Style.from_mapinfo(line.lstrip())
    index = index + 1
    line = source[index]
    token_item = search('Title "{title_map}"', line.lstrip() + " ")
    if token_item is not None:
        map_title = token_item.named['title_map']
    index = index + 1
    line = source[index]
    isFillOnParser = search('FillFrame {fill_on}', line.lstrip() + " ")
    if isFillOnParser is not None:
        ''' как заполнять frame картой'''
        isFillOn = False
        if line.lstrip().lower().find("on") > 0:
            isFillOn = True
    ''' ищем карту с названием'''
    active_map = None
    active_mapview = None
    objItemReport = None
    active_object_frame = getObjectByTitleFrame(map_title)
    if active_object_frame is None:
        print("Not found Franme Title:" + map_title)
        clsDlg = DlgSelectView(axipy.app.mainwindow.qt_object())
        # clsDlg.show(map_title)
        clsDlg.exec_(map_title)
        active_object_frame = clsDlg.selectView

    if active_object_frame is not None:
        if isinstance(active_object_frame, MapView):
            objItemReport = MapReportItem(rect_frame, active_object_frame.map)
            objItemReport.scale = active_object_frame.scale
            objItemReport.center = active_object_frame.center
        if isinstance(active_object_frame, TableView):
            objItemReport = TableReportItem(rect_frame, active_object_frame.data_object)

        objItemReport.border_style = style_border
    return objItemReport


