# -*- coding: utf-8 -*-

import logging
import saas.tools.ssm.modules.startrek_api as startrek_api
from saas.library.python.sandbox import SandboxExecutor, SandboxTaskFailure


class FerrymanConfigRequest:
    """
    Class for ferryman configs and amespaces requests.
    """
    sandbox = None

    def __init__(self):
        self.init_sandbox()

    @classmethod
    def init_sandbox(cls):
        if cls.sandbox is None:
            cls.sandbox = SandboxExecutor(default_owner='RTYSERVER-ROBOT')

    @classmethod
    def new_namespace(cls, namespace_name, ferryman_name, ferryman_ctype,
                      namespace_owners=None, namespace_size=None, namespace_doccount=None, ticket=None, dry_run=False):
        cls.init_sandbox()
        custom_fields = {
            'namespace_name': namespace_name,
            'ferryman_name': ferryman_name,
            'ferryman_ctype': ferryman_ctype,
        }
        if namespace_owners:
            if type(namespace_owners) is list:
                custom_fields['namespace_owners'] = ', '.join(namespace_owners)
            else:
                custom_fields['namespace_owners'] = namespace_owners
        if namespace_size:
            custom_fields['ns_size'] = namespace_size
        if namespace_doccount:
            custom_fields['ns_doc_count'] = namespace_doccount
        if ticket:
            custom_fields['startrek_ticket'] = ticket
        if dry_run:
            custom_fields['dry_run'] = dry_run

        logging.info('Running sandbox task with custom_fields={}'.format(custom_fields))

        task = cls.sandbox.run_from_params(
            custom_fields,
            description='Allocating namespace {} for service {} ctype {}, ticket {}'.format(namespace_name, ferryman_name,
                                                                                            ferryman_ctype, ticket),
            task_type='MANAGE_FERRYMAN_NAMESPACES'
        )

        try:
            if ticket:
                startrek_cl = startrek_api.SaaSStartrekWorkflow()
                startrek_cl.start_progress_issue(ticket)
                task.wait()
                startrek_cl.add_comment(ticket, 'Неймспейс успешно заведен.')
                startrek_cl.resolve_issue(ticket)
            else:
                task.wait()
            return True
        except SandboxTaskFailure:
            logging.critical('Allocation task %s failed', task)
        return False

    @classmethod
    def add_ferryman_config(cls, ferryman_name, ferryman_ctype, yt_cluster, input_size,
                            ferryman_type, row_processor, service_type, dry_run=False):
        cls.init_sandbox()
        custom_fields = {
            'ferryman_name': ferryman_name,
            'ferryman_ctype': ferryman_ctype,
            'ferryman_type': ferryman_type,
            'yt_cluster': yt_cluster,
            'input_size': input_size,
            'row_processor': row_processor,
            'service_type': service_type,
            'dry_run': dry_run
        }
        logging.info('Running sandbox task with custom_fields={}'.format(custom_fields))
        task = cls.sandbox.run_from_params(
            custom_fields,
            description='Adding ferryman config for service {} ctype {}'.format(ferryman_name, ferryman_ctype),
            task_type='ADD_FERRYMAN_CONFIG'
        )
        try:
            logging.debug('Waiting for task %s', task)
            task.wait()
            return task.context['target_task_id'], task.context['target_resource_id']
        except SandboxTaskFailure:
            logging.exception('New configuration task %s failed', task)
