import os.path
import xml.etree.ElementTree as ET
from pathlib import Path, PurePath

from addTools.tabFiles import factorySource, FileSourceMws, FileSource


#from CopyMws.Test.addTools.tabFiles import factorySource


def getFileName(node)->str:
    node_file_name=node.find('{http://www.mapinfo.com/mxp}FileName')
    if node_file_name is None:
        return None,None
    id = node.attrib['id']
    dataPrividerName=node.attrib['providerId']
    filename=node_file_name.text
    return filename,id,dataPrividerName
def getListTabInMws(tree_nodes,path_folder_mws):
    list_tab_in_wms=[]
    nodes_TABFileDataSourceDefinition = tree_nodes.findall(
        '/{http://www.mapinfo.com/mxp}DataSourceDefinitionSet/{http://www.mapinfo.com/mxp}TABFileDataSourceDefinition')
    for node in nodes_TABFileDataSourceDefinition:
        file_name,id,nameProvider = getFileName(node)
        file_source=FileSourceMws(file_name,id)
        #full_path = str(path_folder_mws.joinpath(file_name))
        #abs_path = PurePath(full_path)
        file_source.setParentFolder(path_folder_mws)
        list_tab_in_wms.append({'source':file_source,'provider':nameProvider})
    nodes_TABFileDataSourceDefinition = tree_nodes.findall(
        '/{http://www.mapinfo.com/mxp}DataSourceDefinitionSet/{http://www.mapinfo.com/mxp}RasterFileDataSourceDefinition')
    for node in nodes_TABFileDataSourceDefinition:
        file_name, id, nameProvider = getFileName(node)
        file_source = FileSourceMws(file_name, id)
        # full_path = str(path_folder_mws.joinpath(file_name))
        # abs_path = PurePath(full_path)
        file_source.setParentFolder(path_folder_mws)
        list_tab_in_wms.append({'source': file_source, 'provider': nameProvider})
    return list_tab_in_wms
def copyTabSource(list_tab_source,path_dest:Path,folder_for_tab='table'):
    path_dest_for_tab=path_dest.joinpath(folder_for_tab)
    '''
    if not path_dest_for_tab.exists():
        path_dest_for_tab.mkdir()
    '''
    for tab_source_item in list_tab_source:
        tab_source=tab_source_item['source']
        cslSource = factorySource(tab_source_item)
        if cslSource is None:
            return
        if isinstance(cslSource,FileSource):
            path_dest_for_tab = path_dest.joinpath("any_data")
        if len(tab_source.subfolders)==0:
            if not path_dest_for_tab.exists():
                path_dest_for_tab.mkdir()
            cslSource.copy(path_dest_for_tab)
        else:
            if not (tab_source.subfolders[0]=='table' or tab_source.subfolders[0]=='any_data'):
                new_path_dest=path_dest.joinpath(tab_source.subfolders[0])
                cslSource.copy(new_path_dest)
            else:
                if not path_dest_for_tab.exists():
                    path_dest_for_tab.mkdir()
                cslSource.copy(path_dest_for_tab)
            #cslSource.copy(new_path_dest)
        tab_source.setDestPath(cslSource.destPath)
def updateMws(tree_nodes,listTabUpdate,path_folder_dest):
    nodes_TABFileDataSourceDefinition = tree_nodes.findall(
        '/{http://www.mapinfo.com/mxp}DataSourceDefinitionSet/{http://www.mapinfo.com/mxp}TABFileDataSourceDefinition')
    for node in nodes_TABFileDataSourceDefinition:
        id = node.attrib['id']
        items_list=list(filter(lambda tab_mws:  tab_mws['source'].idSource ==id,listTabUpdate ))
        if len(items_list)==0:
            print("Not find ID:"+id)
            continue
        node_file_name = node.find('{http://www.mapinfo.com/mxp}FileName')
        relative_path=os.path.relpath(items_list[0]['source'].destPath,path_folder_dest)
        node_file_name.text=relative_path
        nodes_TABFileDataSourceDefinition = tree_nodes.findall(
            '/{http://www.mapinfo.com/mxp}DataSourceDefinitionSet/{http://www.mapinfo.com/mxp}TABFileDataSourceDefinition')
        for node in nodes_TABFileDataSourceDefinition:
            id = node.attrib['id']
            items_list = list(filter(lambda tab_mws: tab_mws['source'].idSource == id, listTabUpdate))
            if len(items_list) == 0:
                print("Not find ID:" + id)
                continue
            node_file_name = node.find('{http://www.mapinfo.com/mxp}FileName')
            relative_path = os.path.relpath(items_list[0]['source'].destPath, path_folder_dest)
            node_file_name.text = relative_path
        nodes_TABFileDataSourceDefinition = tree_nodes.findall(
            '/{http://www.mapinfo.com/mxp}DataSourceDefinitionSet/{http://www.mapinfo.com/mxp}RasterFileDataSourceDefinition')
        for node in nodes_TABFileDataSourceDefinition:
            id = node.attrib['id']
            items_list = list(filter(lambda tab_mws: tab_mws['source'].idSource == id, listTabUpdate))
            if len(items_list) == 0:
                print("Not find ID:" + id)
                continue
            node_file_name = node.find('{http://www.mapinfo.com/mxp}FileName')
            relative_path = os.path.relpath(items_list[0]['source'].destPath, path_folder_dest)
            node_file_name.text = relative_path
        jkl=0
path_source_mws='E:\\Support\\Terix\\Repo\\Maps\\Russia.mws'
path_source_mws='E:\\Support\\mts\\MtsMap\\proba85Test.mws'
path_source_mws='E:\\Support\\TestWor\\TestTheme.mws'
path_source_mws=r"E:\Support\WorExample\WorCopy\demo_wor\набор.mws"
path_source_mws=r"E:\Support\WorExample\WorCopy\CopyMws\набор.mws"
pathDest='E:\\Support\\Terix\\Repo\\Maps\\CopyMapMts'
pathDest='E:\\Support\\Terix\\Repo\\Maps\\CopyMap'
pathDest=r"E:\Support\WorExample\WorCopy\CopyMws"
pathDest=r"E:\Support\WorExample\WorCopy\CopyMws2"
#pathDest=r"E:\Support\WorExample\WorCopy\demo_wor\набор.mws"
pathOut_mws=os.path.join(pathDest,str(Path(path_source_mws).name))
tree = ET.parse(path_source_mws)
root = tree.getroot()
list_tab=getListTabInMws(tree,Path(path_source_mws).parent)
dest_folder=Path(pathDest)
if not dest_folder.exists():
    dest_folder.mkdir()
copyTabSource(list_tab,Path(pathDest))
updateMws(tree,list_tab,pathDest)
text_mws=str(ET.tostring(root, encoding='utf-8'), 'UTF-8')
text_mws=text_mws.replace('ns0:','')
#text_mws=text_mws.replace('ns1:Point','ml:Point')
text_mws=text_mws.replace('ns1:','gml:')
#text_mws=text_mws.replace('gml:','')
text_mws='<?xml version="1.0" encoding="UTF-8"?>'+text_mws
'''
with open(pathOut_mws, 'wb') as f:
    tree.write(f, encoding='utf-8')
'''
line_mws=text_mws.split('\n')
line_mws[0]='<?xml version="1.0" encoding="UTF-8"?><WorkSpace xmlns:gml="http://www.opengis.net/gml" xmlns:mxp="http://www.mapinfo.com/mxp" xmlns="http://www.mapinfo.com/mxp">'
with open(pathOut_mws, "w", encoding="utf-8") as mws_file:
    #mws_file.write(text_mws)
    mws_file.writelines(line_mws)

print("End")
