import os
import shutil
from pathlib import Path
from time import sleep
from tqdm import tqdm

import humanize

FILE_LT_1024 = []
LIST_FOLDERS = [
    'vmlogs',
    '.BigNox',
    'Nox_share',
    'Music',
    'AppData',
    r'C:\Program Files',
    'Downloads'
]


def path_to_folder(folder):
    for dir in LIST_FOLDERS:
        if dir in folder or dir.lower() in folder:
            return os.path.join(homepath, dir)
    return False


def size_unity_hd():
    total, used, free = shutil.disk_usage("/")

    print('TOTAL (C)..: %d Gib' % (total // (2 ** 30)))
    print('USADO (C)..: %d Gib' % (used // (2 ** 30)))
    print('LIVRE (C)..: %d Gib' % (free // (2 ** 30)))
    print('*' * 100)

    total, used, free = shutil.disk_usage("E:")

    print('TOTAL (E)..: %d Gib' % (total // (2 ** 30)))
    print('USADO (E)..: %d Gib' % (used // (2 ** 30)))
    print('LIVRE (E)..: %d Gib' % (free // (2 ** 30)))

    print(shutil.which("python"))


def get_folder_size(folder):
    # return ByteSize(sum(file.stat().st_size for file in Path(folder).rglob('*')))
    return sum(file.stat().st_size for file in Path(folder).rglob('*'))


def get_directory_size(directory):
    """Returns the `directory` size in bytes."""
    total = 0
    try:
        save_file = []
        for entry in tqdm(os.scandir(directory)):
            # for entry in os.scandir(directory):
            if entry.is_file():
                size_file_normal = entry.stat().st_size
                if len(save_file) < 1:
                    save_file.append(entry)
                else:
                    size_file_in_save_file = save_file[0].stat().st_size
                    if size_file_normal > size_file_in_save_file:
                        cp_list = save_file
                        save_file = []
                        save_file.append(entry)
                        save_file.append(cp_list)
                    else:
                        save_file.append(entry)
                # size_file = humanize.naturalsize(size_file_normal)
                # if len(size_file.split(' ')[0]):
                #     # file = '-FILE'.join((directory.split('\\')[-1], entry.name))
                #     file = entry.name
                #     size = size_file
                #     FILE_LT_1024.append({
                #         file: size
                #     })
                # print(f"\nFile..: {file} - Size..:{size_file}")
                # total += entry.stat().st_size
            elif entry.is_dir():
                # print("[+] Getting the size of", entry.name)
                total += get_directory_size(entry.path)
                # print(f"\nDir..: {entry.name} - Size..:{humanize.naturalsize(total)}")
        sleep(1)
    except NotADirectoryError:
        # if `directory` isn't a directory, get the file size then
        return os.path.getsize(directory)
    except PermissionError:
        # if for whatever reason we can't open the folder, return 0
        return 0
    except FileNotFoundError as err:
        print(f'FileNotFoundError..: {err}')
        # return 0
    for size in save_file:
        try:
            print(f'{size.path} - {humanize.naturalsize(size.stat().st_size)}')
        except AttributeError as err:
            print(f'{size} - ERROR..: {err}')
        # print(f'{size}')
    return total


if __name__ == '__main__':
    homepath = os.path.expanduser(os.getenv("USERPROFILE"))
    program_files = r"C:\Program Files"
    program_files86 = r"C:\Program Files (x86)"
    vmlogs = 'vmlogs'
    bignox = '.BigNox'
    noxshare = 'Nox_share'
    musicas = 'Music'
    appdata = 'AppData'
    downloads = 'Downloads'
    # os.path.join(homepath,'AppData')
    path_found = ''
    # dirname, filename = os.path.split(os.path.abspath(__file__))
    excludes = ['$RECYCLE.BIN']
    for path, dnames, fnames in os.walk('E:/', topdown=True):
        dnames[:] = [dirname for dirname in dnames if dirname not in excludes]
        try:
            for dir in dnames:
                size_dir = humanize.naturalsize(get_directory_size(os.path.join(path, dir)))
                print(f'{"-" * 10}\n{path}{dir} - Size..: {size_dir}')
                for file in FILE_LT_1024:
                    print(f'{"* ".rjust(1)}{file}')
                # for file in os.scandir(os.path.join(path,dir)):
                #     print(f'{"* ".rjust(1)}{file.name}')
            break
        except PermissionError as err:
            print(f'PermissionError..: {err}')
    # print(path_found)
    # if path_to_folder(downloads):
    #     size_folder = humanize.naturalsize(get_directory_size(downloads))
    # for res in sorted(FILE_LT_1024, key=operator.itemgetter("size")):
    # for res in sorted(FILE_LT_1024, key=lambda k: list(k.values())):
    # for res in FILE_LT_1024:
    #     print(f'{res}\n{"*"*80}')
    # print(size_folder)
    # try:
    #     print(item)
    #     fso = com.Dispatch("Scripting.FileSystemObject")
    #     folder = fso.GetFolder(item)
    #     # size = str(round(folder.Size / 1048576))
    #     size = humanize.naturalsize(folder.Size)
    #     print(f"Size..: {size}")
    # except Exception as err:
    #     print(f'ERROR..: {str(err)}')
    # )
    # size = get_folder_size(program_files86)
    # print(humanize.naturalsize(size))
    # print(size)
    # print(size.gigabytes)
    # print(size.MB)
