# coding: utf8

from yandex.maps.wiki import db, fastcgihelpers as fh
from yandex.maps.wiki.pgpool3 import get_pgpool
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

from maps.wikimap.mapspro.libs.python import acl

TASK_NAME = 'prepare_stable_branch'

ACL_PATH = "mpro/tasks/prepare-stable-branch"


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


@register_task_type(name=TASK_NAME)
class PrepareStableBranch:
    @staticmethod
    def capabilities_ET():
        return EM.prepare_stable_branch_task_type()

    @staticmethod
    def create(uid, request):
        if not acl.is_permission_granted(get_pgpool(db.CORE_DB), ACL_PATH, uid):
            raise fh.ServiceException('forbidden', status='ERR_FORBIDDEN')

        task = PrepareStableBranchTask()
        task.on_create(uid)
        return task

    @staticmethod
    def launch(session, task_id, request):
        args = {
            'taskId': task_id,
            'type': TASK_NAME,
            'uid': int(request.values['uid'])
        }
        gateway = create_grinder_gateway()
        return gateway.submit(args)


class PrepareStableBranchTask(Task):
    __mapper_args__ = {'polymorphic_identity': TASK_NAME}
