# coding: utf8

import sqlalchemy as sa

from yandex.maps.wiki import config
from yandex.maps.wiki.tasks import EM, register_task_type, grinder
from yandex.maps.wiki.tasks.models import Task

TASK_NAME = 'apply_shadow_attributes'


def create_grinder_gateway():
    return grinder.GrinderGateway(config.get_config().grinder_params.host)


@register_task_type(name=TASK_NAME)
class ApplyShadowAttributes:
    @staticmethod
    def capabilities_ET():
        return EM.apply_shadow_attributes_task_type()

    @staticmethod
    def create(uid, request):
        task = ApplyShadowAttributesTask()
        task.on_create(uid)
        task.branch_id = int(request.values['branch'])
        return task

    @staticmethod
    def launch(session, task_id, request):
        task = session.query(ApplyShadowAttributesTask).get(task_id)

        gateway = create_grinder_gateway()
        return gateway.submit(task.get_grinder_args())


class ApplyShadowAttributesTask(Task):
    __tablename__ = 'apply_shadow_attributes_task'
    __table_args__ = {'schema': 'service'}
    __mapper_args__ = {'polymorphic_identity': TASK_NAME}

    id = sa.Column(sa.BigInteger, sa.ForeignKey('service.task.id'), primary_key=True)
    branch_id = sa.Column(sa.BigInteger)

    def __context_ET(self):
        return EM.apply_shadow_attributes_context(
            EM.branch(self.branch_id))

    def context_ET_brief(self, *args, **kwargs):
        return self.__context_ET()

    def context_ET_full(self, *args, **kwargs):
        return self.__context_ET()

    def get_grinder_args(self):
        return {
            'taskId': self.id,
            'type': TASK_NAME,
            'uid': self.created_by,
            'branchId': self.branch_id
        }

    def resume(self):
        gateway = create_grinder_gateway()
        result = gateway.submit(self.get_grinder_args())
        self.grinder_task_id = result.id
