import glob
import os
import shutil
from pathlib import Path

from CopyMws.ui.processtool.addTools.CopySpatialTab import CopyTabSpatial


class FileSourceMws:
    def __init__(self,path,id_source):
        self.__parentFolder=None
        self.__path=path
        self.__subfolder=None
        self.__path_absolut=None
        self.__isGlobalRealative=False
        self.__id_mws=id_source
        if  Path(self.__path).is_absolute():
            self.__path_is_absolute=True
        else:
            self.__path_is_absolute = False
            self.__getsubFolders()
            self.__prepareSubFolder()
    def setParentFolder(self,parent_folder):
        self.__parentFolder=parent_folder
        if not self.__path_is_absolute:
            self.__path_absolut=str(Path(parent_folder).joinpath(self.__path).resolve())
            return
        self.__path_absolut=self.__path
        path_curent=Path(self.__path)
        if path_curent.drive==parent_folder.drive:
            path_relative= os.path.relpath(self.__path,str(parent_folder))
        else:
            path_relative=self.__path
        self.__path=path_relative
        self.__path_is_absolute = False
        self.__getsubFolders()
        self.__prepareSubFolder()
    def __getsubFolders(self):
        self.__subfolder=[]

        for item in Path(self.__path).parts:
            if item=='.' or item=='..':
                if item=='..':
                    self.__isGlobalRealative=True
                continue
            name=Path(item).name
            #self.__subfolder.append(item)
            self.__subfolder.append(name)
    def __prepareSubFolder(self):
        self.__subfolder_work=[]
        n=len(self.__subfolder)-1
        for i in range(n):
            if i==0 and self.__isGlobalRealative:
                continue
            self.__subfolder_work.append(self.__subfolder[i])
    @property
    def idSource(self):
        return self.__id_mws
    @property
    def pathAbsolut(self):
        return self.__path_absolut
    @property
    def isGlobalRealative(self):
        return self.__isGlobalRealative
    @property
    def subfolders(self):
        return self.__subfolder_work
    def setDestPath(self,path_dest):
        self.__realCopyPath=path_dest
    @property
    def destPath(self):
        return self.__realCopyPath
class BaseTab:
    def __init__(self,path):
        self.__path_tab=path
        self.__realCopyPath=None
    @property
    def pathSource(self):
        return self.__path_tab
    @property
    def nameCls(self):
        return "BASE"
    def copy(self,dest_path,filter_spatial=None):
        pass
    def setDestPath(self,path_dest):
        self.__realCopyPath=path_dest
    @property
    def destPath(self):
        return self.__realCopyPath
class FileSource:
    def __init__(self,file_source:FileSourceMws,path_include_file):
        self.__file_source_descriptor=file_source
        self.__path_include_file=Path(path_include_file)


    @property
    def nameCls(self):
        return "self.__file_source_descriptor."
    def copy(self, dest_path_folder, filter_spatial=None):
        folder_dest=Path(dest_path_folder)
        if not folder_dest.exists():
            folder_dest.mkdir()
        folder_include_file=str(self.__path_include_file.parent)
        if str(folder_include_file)=='.':
            ''' вложенный файл лежит там же где и таб '''
            path_source=Path(self.__file_source_descriptor.pathAbsolut)
            path_source_include=path_source.parent.joinpath(str(self.__path_include_file))
            path_dest=folder_dest.joinpath(str(self.__path_include_file))

            shutil.copyfile(path_source_include,path_dest)
            ''' Копируем tab '''
            path_source_name = Path(self.__file_source_descriptor.pathAbsolut).name
            path_dest=folder_dest.joinpath(path_source_name)
            shutil.copyfile(self.__file_source_descriptor.pathAbsolut, path_dest)
            self.__realCopyPath=str(path_dest)
            jkl=0

    @property
    def destPath(self):
        return self.__realCopyPath
class MiTab(BaseTab):
    def __init__(self,file_source:FileSourceMws):
        super().__init__(file_source)
        self.__path_source=Path(file_source.pathAbsolut)
    @property
    def nameCls(self):
        return "MapInfo"


    def copy(self, dest_path_folder, filter_spatial=None):
        ''' Копирование MapInfo tab '''
        if filter_spatial is None:
            ''' Копируем целиком таблицу '''
            self.__copyFull(dest_path_folder)
        else:
            cur_path = self.__tryAndCreatesubFolderf(dest_path_folder, self.pathSource.subfolders)
            cur_path_tab=cur_path.joinpath(self.__path_source.name)
            tabCopyCls=CopyTabSpatial()
            tabCopyCls.copy(str(self.__path_source),str(cur_path_tab),filter_spatial)
            self.setDestPath(os.path.join(cur_path, str(Path(self.pathSource.pathAbsolut).name)))
    def __copyFull(self,dest_path):
        ''' Копируем без пространственного фильтра все файлы '''
        source_folder=str(self.__path_source.parent)
        name=str(self.__path_source.stem)
        path_for_find=str(self.__path_source.parent.joinpath(name))+".*"
        list_file_by_name=glob.glob(path_for_find)
        path_dest=dest_path

        cur_path=self.__tryAndCreatesubFolderf(dest_path,self.pathSource.subfolders)
        for file_source in list_file_by_name:
            path_dest_file=str(cur_path.joinpath(Path(file_source).name))
            dest= shutil.copyfile(file_source,path_dest_file)
            self.setDestPath(path_dest_file)
        self.setDestPath(os.path.join(cur_path,str(Path(self.pathSource.pathAbsolut).name)))
    def __tryAndCreatesubFolderf(self,our_base_folder,subFolder):
        cur_path=our_base_folder

        if not cur_path.exists():
            cur_path.mkdir()
        for folder in subFolder:
            cur_path=cur_path.joinpath(folder)
            if not cur_path.exists():
                cur_path.mkdir()
        return cur_path
def factorySource(file_source_item):
    file_source=file_source_item['source']
    name_provider=file_source_item['provider'].lower()
    if not Path(file_source.pathAbsolut).exists():
        return None
    with open(file_source.pathAbsolut) as f:
        lines = [line.strip() for line in f]
    file_name_includet=None
    type=None
    items_file=list(filter(lambda line: line.lower().find('file')==0, lines))
    items_type = list(filter(lambda line: line.lower().find('type') == 0, lines))
    if len(items_type)==0:
        return MiTab(file_source)
    item_types=items_type[0].split(' ')
    type_datasource=item_types[1].lower()
    if type_datasource=='native':
        return MiTab(file_source)
    if type_datasource=='shapefile':
        return MiTab(file_source)
    if len(items_file)==1:
        str_path_file=items_file[0].replace("File",'').strip()
        path_file=str_path_file[:-1]
        path_file=path_file[1:]
        return FileSource(file_source,path_file)
    return None