import pathlib

from werkzeug.utils import secure_filename
from flask import request
from helpers.file_utils import is_whitelisted_extension
from typing import Optional, Union, Set, Tuple
import os


def save_multiple_uploaded_files(output_folder: str, reserved_filenames: Set[str], allowed_extensions: Set[str]) -> Tuple[str, Set[str]]:
    files = request.files.getlist("file[]")
    output_filenames = set()

    if len(files) == 0:
        return "No files provided?", output_filenames

    pathlib.Path(output_folder).mkdir(exist_ok=True, parents=True)

    for file in files:
        if not file or file.filename == '':
            return "No filename provided?", output_filenames

        filename = secure_filename(file.filename)

        if not is_whitelisted_extension(filename, allowed_extensions):
            return f"Filetype of file {filename} not allowed", output_filenames
        if filename in reserved_filenames:
            return f"Name {filename} is reserved.", output_filenames
        if filename in output_filenames:
            return f"Name {filename} is duplicate.", output_filenames

        output_filenames.add(filename)
        output_path = os.path.join(output_folder, filename)
        file.save(output_path)

    return "", output_filenames
