# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals


from saas.library.python.token_store import PersistentTokenStore
from saas.library.python.sandbox.api import SandboxApi


class SandboxExecutor(object):
    def __init__(self, default_owner, default_task_type=None, default_notifications=None, oauth_token=None):
        oauth_token = oauth_token if oauth_token else PersistentTokenStore.get_token_from_store_env_or_file('sandbox')
        self.sandbox_api = SandboxApi(oauth_token)

        self.default_task_type = default_task_type
        self.default_owner = default_owner
        self.default_notifications = default_notifications

    def add_task(self, params, description=None, task_type=None, owner=None, notifications=None):
        task_type = task_type or self.default_task_type
        owner = owner or self.default_owner
        notifications = notifications or self.default_notifications

        assert task_type is not None and owner is not None

        return self.sandbox_api.add_task(
            task_type=task_type, task_owner=owner, task_params=params,
            description=description, notifications=notifications
        )

    def run_from_params(self, *args, **kwargs):
        task = self.add_task(*args, **kwargs)
        task.start()
        return task

    def wait_from_params(self, *args, **kwargs):
        task = self.run_from_params(*args, **kwargs)
        task.wait()
        return task
