import os
import uuid
import config


def flow_upload_dir(flow_id):
    d = os.path.join(config.UPLOAD_DIR, 'flows', flow_id)
    os.makedirs(d, exist_ok=True)
    return d


def save_flow_file(flow_id, file_storage):
    """file_storage: a werkzeug FileStorage from request.files['file']."""
    ext = os.path.splitext(file_storage.filename or '')[1]
    stored_name = f'{uuid.uuid4().hex}{ext}'
    dest = os.path.join(flow_upload_dir(flow_id), stored_name)
    file_storage.save(dest)
    return stored_name


def flow_file_path(flow_id, stored_name):
    return os.path.join(flow_upload_dir(flow_id), stored_name)


def delete_flow_file(flow_id, stored_name):
    if not stored_name:
        return
    path = flow_file_path(flow_id, stored_name)
    try:
        os.remove(path)
    except OSError:
        pass
