import os
from pathlib import Path
from typing import List


class FileUtils:
    @staticmethod
    def file_path_extend(media_path: str, extend: str) -> str:
        """
        基于现有文件路径添加后缀, 例如 extend = "def" : 123/abc.txt -> 123/abc_def.txt
        :param media_path: 现有文件路径
        :param extend: 后缀名

        :return: 处理过的新文件路径
        """
        media_filename = os.path.basename(media_path)
        media_dir = os.path.dirname(media_path) + '/'
        filenames = media_filename.split('.')
        filenames[0] = f"{filenames[0]}_{extend}"
        extend_filename = '.'.join(filenames)
        return os.path.join(media_dir, extend_filename)

    @staticmethod
    def replace_root_by_depth(media_path: str, root: str, depth: int = 1) -> str:
        """
        使用根目录名替换路径起始位置, 例如:

        prefix="pre",depth=0 : ./abc/def.txt -> pre\\.\\abc\\def.txt

        prefix="pre",depth=1 : ./abc/def.txt -> pre\\abc\\def.txt

        prefix="pre",depth=2 : ./abc/def.txt -> pre\\def.txt

        prefix="pre",depth=3 : IndexError("Depth is out of range")

        :param media_path: 现有文件路径
        :param root: 替换用的根目录名
        :param depth: root所占的路径深度层级

        :return: 处理后的文件路径
        :exception IndexError: 根目录深度超过实际路径深度
        """
        media_dirs = media_path.split('/')
        if depth >= len(media_dirs):
            raise IndexError("Depth is out of range")
        media_dir_prefix = os.path.join(root, *media_dirs[depth:])
        return media_dir_prefix

    @staticmethod
    def file_path_change_extension(media_path: str, extension: str) -> str:
        media_filename = os.path.basename(media_path)
        media_dir = os.path.dirname(media_path) + "/"
        filenames = media_filename.split(".")
        filenames[-1] = extension
        filename = ".".join(filenames)
        return os.path.join(media_dir, filename)

    @staticmethod
    def get_folder_size(folder_path: str) -> int:
        """

        Args:
            folder_path:

        Returns:

        """
        total_size = 0
        for path in Path(folder_path).rglob('*'):
            if path.is_file():
                total_size += path.stat().st_size
        return total_size

    @staticmethod
    def get_file_size(file_path: str) -> int:
        return os.path.getsize(file_path)

    @staticmethod
    def get_files_size(files: List[str]) -> int:
        total_size = 0
        for file in files:
            total_size += os.path.getsize(file)
        return total_size

