from __future__ import print_function
from swimlane_platform.lib import Configuration, names, DockerComposeFileManager, \
    BaseWithLog, info_function_start_finish, logging_questions
from os import path, makedirs
from uuid import uuid4


class AddFileEncryption(BaseWithLog):

    def __init__(self, config):
        # type: (Configuration) -> None
        super(AddFileEncryption, self).__init__(config)
        self.secrets = path.join(names.INSTALL_DIR, names.SECRETS_SUB_FOLDER)

    @info_function_start_finish('Add file encryption')
    def run(self):
        # type: () -> None
        """
        Runs modifications to environment to add file encryption key.
        """
        if not path.exists(self.secrets):
            makedirs(self.secrets)
        key = str(uuid4().hex) if self.config.args.autogenerated_file_encryption_key \
            else self.config.args.file_encryption_key
        key_file = path.join(self.secrets, 'file_encryption.key')
        if path.exists(key_file):
            self.logger.warn('File encryption key file already exists. We will not overwrite it.')
            return
        with open(key_file, 'w') as key_file_stream:
            key_file_stream.write(key)
        docker_compose = DockerComposeFileManager(self.logger, path.join(names.INSTALL_DIR, 'docker-compose.yml'))
        docker_compose.set(key_file, 'secrets', 'file_encryption_key', 'file')
        docker_compose.save()


def run(config):
    # type: (Configuration) -> None
    """
    The script run method, that can be called by other script or from file run method.
    :param config: Additional configuration information collected by parent script.
    """
    questions = [
        {
            'type': 'confirm',
            'message': 'Would you like to auto-generate a file encryption key in GUID format? If not, you must enter '
                       'your own file encryption key.',
            'name': 'autogenerated_file_encryption_key',
            'default': True
        },
        {
            'type': 'input',
            'name': 'file_encryption_key',
            'message': 'Please enter your file encryption key.',
            'when': lambda a: not a['autogenerated_file_encryption_key']
        }
    ]
    questions.extend(logging_questions)
    config.collect(questions)
    AddFileEncryption(config).run()
