import os
import re
import pathlib

def get_file_extension(filename):
    return ''.join(pathlib.Path(filename).suffixes)

def get_list_files(path: str, filter=None, filter_not_contain: str = None, add_path: bool = False, path2: str = ''):
    path = os.path.normpath(path)
    list_files = []
    if add_path:
        path2 = path2 or path
        path2 = os.path.normpath(path2)
    else:
        path2 = ''
    if filter_not_contain:
        filter = r'^((?!{filter_not_contain}).)*$'.format(filter_not_contain=filter_not_contain)
    if filter:
        filters = filter if isinstance(filter, list) else [filter]
        for f in filters:
            list_files.extend([os.path.join(path2, x) for x in os.listdir(path) if re.search(f, x)])
    else:
        list_files = [os.path.join(path2, x) for x in os.listdir(path)]
    return list(set(list_files))

def get_list_files_recursive(path: str, filter=None, filter_not_contain: str = None, add_path: bool = False, path2: str = ''):
    """
    Get filelist with path in folder
    :param path: Folder containing files
    :param filter: filter (regexp-like), could be list of str or just str. None by default
    :param filter_not_contain: filter which should not be in filenames (regexp-like)
    :param add_path: bool, will needed add path to file or not
    :param path2: path which need to add
    :return: return list of files with/without path to it
    """
    path = os.path.normpath(path)
    list_files = []
    if add_path:
        if path2 == '':
            path2 = path
        else:
            path2 = os.path.normpath(path2)
    else:
        path2 = ''

    if filter_not_contain:
        filter = r'^((?!{filter_not_contain}).)*$'.format(filter_not_contain=filter_not_contain)

    if filter:
        if type(filter) == list:
            for f in filter:
                for path_, subdirs, files in os.walk(path):
                    list_files.extend([os.path.join(path_, file) for file in files if re.search(f, file)])
        if type(filter) == str:
            for path_, subdirs, files in os.walk(path):
                list_files.extend([os.path.join(path_, file) for file in files if re.search(filter, file)])
    else:
        for path_, subdirs, files in os.walk(path):
            list_files.extend([os.path.join(path_, x) for x in files])

    list_files_ = []
    for file in list_files:
        path_ = os.path.split(file)
        path_ = [os.path.split(path_[0])[1], path_[1]]
        if add_path:
            path_ = [path2, *path_]
        list_files_.append(os.path.join(*path_))

    list_files = list(set(list_files_))

    return list_files

def check_folder_exist(folder_path: str):
    folder_path = os.path.normpath(folder_path)
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

ls = get_list_files
lsr = get_list_files_recursive
