import os
import math
import subprocess as sp
from omp import app

def read_file(path:str=''):
    with open(path, 'r') as f:
        return f.readlines()

def file_size(path:str=''):
    file_size =  os.path.getsize(path)
    human_size = humanize_size(file_size)
    return human_size

def humanize_size(size:int) -> str:
    if size == 0:
        return '0B'
    size_name = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
    i = int(math.floor(math.log(size, 1024)))
    p = math.pow(1024, i)
    s = round(size/p,2)
    return f"{s} {size_name[i]}"

def is_whitelisted(path):
    #if os.path.dirname(path) in app.config['PATH_WHITELIST']:
    #if path in app.config['PATH_WHITELIST']:
    if path[:6] == '/odds/':
        return True
    else:
        return False

def not_whitelisted(path):
    return not is_whitelisted(path)


def get_file_name_from_path(path:str) -> str:
    parts = path.split('/')
    return parts[-1]


def get_command_output(command:str) -> str:
    """Executes whitelisted shell command to
       check for different info.
    """
    if command not in app.config['WHITELISTED_COMMANDS']:
        # TODO raise exception
        return 'Command not allowed'

    print(command)
    command = command.split(' ')
    print(command)
    cmd = sp.Popen(command, stdout=sp.PIPE)
    out, err = cmd.communicate()
    out = out.decode('ascii')
    out = out.strip()
    return out

def get_client_list(paths:list) -> list:
    clients = []
    for path in paths:
        client = path.split('/')[-1]
        clients.append(client)
    return clients

def count_files(path:str) -> int:
	return len(os.listdir(path))

