import os 

from aiohttp import web

from web_interface.auth import check_auth
import paths

def check_for_path_escapes(filename, folder):
    try:
        realpath = os.path.realpath(os.path.join(folder, filename))
        if os.path.samefile(os.path.dirname(realpath), folder):
            return True
    except Exception as e:
        raise web.HTTPBadRequest(text=f'Error pathsing filename {filename}: {e}')
    return False


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')
    filepath = os.path.join(storage_path, filename)
    if not check_for_path_escapes(filepath, storage_path):
        raise web.HTTPBadRequest(text='Invalid path: ' + str(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()
