from saas.tools.devops.lib23.saas_service import SaasService
from saas.library.python.sandbox import SandboxApi

import logging
import time

DEFAULT_BUNDLE_RESOURCE_ID = 1253301317
DEFAULT_RTYSERVER_RESOURCE_ID = 1244503519
DEFAULT_MODELS_RESOURCE_ID = 1659830995


class SaasDJService(SaasService):
    DJ_OWNERS = ['rudolf', 'dpaveldev']

    def post_create_hook(self):
        sandbox = SandboxApi()

        def add_admins(attrs, logins=[]):
            attrs['owners']['logins'].extend(logins)
            return attrs

        resource_bundle = sandbox.get_last_released_resource('DJ_TUTORIAL_RESOURCE_BUNDLE')
        if resource_bundle is None:
            self.LOGGER.error("Can't find latest released resource bundle, falling back to default %s",
                              DEFAULT_BUNDLE_RESOURCE_ID)
            resource_bundle = sandbox.resource_by_id(DEFAULT_BUNDLE_RESOURCE_ID)
        self.LOGGER.info("Will use %s as DJ resource bundle", resource_bundle.id)

        rtyserver = sandbox.get_last_released_resource('DJ_RTYSERVER_BIN')
        if rtyserver is None:
            self.LOGGER.error("Can't find latest released rtyserver-dj, falling back to default %s",
                              DEFAULT_RTYSERVER_RESOURCE_ID)
            rtyserver = sandbox.resource_by_id(DEFAULT_RTYSERVER_RESOURCE_ID)
        self.LOGGER.info("Will use %s as DJ rtyserver", rtyserver.id)

        # SAAS-5941
        models = sandbox.resource_by_id(DEFAULT_MODELS_RESOURCE_ID)

        for ns in self.nanny_services:

            self.LOGGER.info('Adding %s as admins to nanny service %s', self.DJ_OWNERS, ns.name)
            ns.patch_auth_attributes(lambda attrs: add_admins(attrs, self.DJ_OWNERS), 'Add dj owners to owners')

            ns.add_or_replace_sandbox_file('resources', resource_bundle.nanny_resource_info())
            ns.add_ticket_integration_rule(
                sandbox_task_type=resource_bundle.nanny_resource_info()['task_type'],
                sandbox_resource_type=resource_bundle.nanny_resource_info()['resource_type'],
                queue_id='SAAS', filter_expression='sandbox_release.release_type in ("stable",)',
                desc="DJ resource bundle release integration"
            )

            ns.add_or_replace_sandbox_file('rtyserver', rtyserver.nanny_resource_info())
            ns.add_ticket_integration_rule(
                sandbox_task_type=rtyserver.nanny_resource_info()['task_type'],
                sandbox_resource_type=rtyserver.nanny_resource_info()['resource_type'],
                queue_id='SAAS', filter_expression='sandbox_release.release_type in ("stable",)',
                desc="DJ binary release integration"
            )

            ns.add_or_replace_sandbox_file('models', models.nanny_resource_info())

            self.LOGGER.info("Clearing data status in slots")
            slots_left = set([sl.id for sl in self.slots])
            for i in range(100):
                for slot in self.slots:
                    if slot.id not in slots_left:
                        continue
                    try:
                        slot.execute_command('clear_data_status')
                        slots_left.remove(slot.id)
                    except:
                        logging.exception('Failed to ClDS on slot %s', slot.id)
                if not slots_left:
                    break
                time.sleep(i)

            self.LOGGER.info("Deploy nanny service %s", ns.name)
            ns.add_common_noconfirm_recipe()
            ns.add_common_global_recipe()
            ns.activate_last_snapshot(recipe='common_global')
