from pathlib import Path
import zipfile
import gzip
import shutil


def unzip_file(element_path):
    """Checking if the path points to an existing folder or to its .zip format; if only the .zip format exists,
    it unzips the folder.

    Parameters
    ----------
    element_path: PosixPath
        Absolute path of the folder or file of interest.

    Returns
    -------
        Absolute path of the (unzipped) folder of interest.
    """
    if element_path.exists():
        return element_path

    elif Path(str(element_path) + ".zip").exists():
        zip_folder = zipfile.ZipFile(str(element_path) + ".zip", 'r')
        zip_folder.extractall(element_path.resolve().parent)
        zip_folder.close()
        return element_path

    elif Path(str(element_path) + ".gz").exists():
        with gzip.open(str(element_path) + ".gz", 'rb') as f_in:
            with open(str(element_path), 'wb') as f_out:
                shutil.copyfileobj(f_in, f_out)
        return element_path

    else:
        raise FileNotFoundError(f"{element_path} does not exist")