# -*- coding: UTF-8 -*-
import json
from gm_dbmw_api.descriptor import descriptor_to_json
from gm_dbmw_api.descriptor.connection import Connection, _TaskGroupCategory
from gm_dbmw_api.descriptor.sink import GMRpcSink


class TriggerBase(object):
    name = ''
    mode_map = {
        'trigger': {'task_category': _TaskGroupCategory.ONLINE},
        'scan': {'task_category': _TaskGroupCategory.ROUND_SCANNING},
        'full': {'task_category': _TaskGroupCategory.FULL_SCANNING},
    }

    @classmethod
    def rpc_sink(cls):
        return GMRpcSink(
            method='hera/viewmodel/sync',  # 请求的RPC接口
            static_params_json=json.dumps({'viewmodel': cls.vmcls_name}),  # 固定的透传的参数
            key_list_param_name='ids',  # 接受参数的key
            is_async_proxy=False,
            key_is_integer=True,
        )

    @classmethod
    def trigger_source(cls):
        pass

    @classmethod
    def scan_source(cls):
        pass

    @classmethod
    def full_source(cls):
        pass

    @classmethod
    def _source(cls, mode):
        method = getattr(cls, '%s_source' % (mode), None)
        return method()

    @classmethod
    def _connect(cls, mode):
        conn = Connection(
            name=cls.name,
            sink=cls.rpc_sink(),
            task_group_category=cls.mode_map[mode]['task_category'],
            source=cls._source(mode),
        )
        return conn

    @classmethod
    def trigger_spec(cls, path=None):
        return cls.to_spec(cls._connect('trigger'))

    @classmethod
    def scan_spec(cls, path=None):
        return cls.to_spec(cls._connect('scan'))

    @classmethod
    def full_spec(cls, path=None):
        return cls.to_spec(cls._connect('full'))

    @classmethod
    def to_spec(cls, action_mode, path=None):
        j = descriptor_to_json(action_mode)
        if path is None:
            return j
        with open(path, 'w') as pf:
            pf.write(j)
