"""
Utility and helper functions for the packaged tasks

:copyright: Copyright 2013-2016, Dorian Pula <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import contextlib
import copy
import os
import shutil

import pathlib


def delete_in_path_list(path_list, dry_run=False):
    """
    Deletes all the elements in the given path list.

    :param path_list: A list of paths to delete.
    :param dry_run: Mode for switching between a dry run and actual deletion run.
    """
    if dry_run:
        print('Running in: Dry run mode.')

    for folder in path_list:
        path = pathlib.Path(folder)
        if not path.exists():
            continue
        print('Deleting... {}'.format(path))

        if not dry_run and path.is_dir():
            shutil.rmtree(path.as_posix())
            continue

        if not dry_run:
            path.unlink()


@contextlib.contextmanager
def cd(path):
    """
    Context manager to change a current working directory.

    :param path: The path to change the current working directory.
    """
    previous_path = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(previous_path)


@contextlib.contextmanager
def environment(environ_modifier):
    """
    Context manager to store all the environment variables, modify them and then restore them.

    :param environ_modifier: A dictionary of environment variables and the values to change.
    """
    current_env = copy.deepcopy(os.environ)
    if not isinstance(environ_modifier, dict):
        raise ValueError(f'Provided environment "{environ_modifier}" is a not a dict!')

    non_string_keys = [key for key in environ_modifier.keys() if not isinstance(key, str)]
    if non_string_keys:
        raise ValueError(f'Provided environment contains invalid keys: "{non_string_keys}"!')

    for environ_key, value in environ_modifier.items():
        os.environ[environ_key] = value
    yield
    os.environ = current_env
