import os 

from aiohttp import web

from web_interface.auth import check_auth
import paths

async def list_dir(request, storage_path):
    check_auth(request)
    sort_key = None
    try:
        json_args = await request.json()
        if isinstance(json_args, dict):
            sort_key = json_args.get('sort')
        elif isinstance(json_args, str):
            sort_key = json_args
    except:
        pass
    if not sort_key:
        sort_key = request.query.get('sort', 'time')
    files_list = []
    for filename in os.listdir(storage_path):
        filepath = os.path.join(storage_path, filename)
        if os.path.isfile(filepath) or os.path.islink(filepath):
            access_time = os.path.getatime(filepath)
            human_access_time = paths.get_human_access_time(filepath)
            size = paths.get_file_size(filepath)
            h_size = paths.get_human_file_size(filepath)
            files_list.append({"name": filename, "size" : size, "h_size" : h_size, "time": access_time, "h_time": human_access_time})
    files_list.sort(key=lambda f: f[sort_key])
    return web.json_response(data=files_list)

async def remove(request, storage_path):
    check_auth(request)
    filename = request.match_info.get('[path]', '').strip('/')
    if not filename:
        filename = request.query.get('filename')
    if not filename:
        try:
            json_args = await request.json()
            if isinstance(json_args, dict):
                filename = json_args.get('filename')
            elif isinstance(json_args, str):
                filename = json_args
        except:
            pass
    if not filename:
        raise web.HTTPBadRequest(text='No filename argument in json or query')
    #TODO validate filename
    filepath = os.path.join(storage_path, filename)
    if not os.path.isfile(filepath) and not os.path.islink(filepath):
        raise web.HTTPBadRequest(text='No such file: ' + str(filename))
    try:
        os.remove(filepath)
    except OSError as e:
        raise web.HTTPInternalServerError(text='Error removing file. Details: ' + str(e))
    raise web.HTTPOk()
