# coding=utf-8
import json

from gm_types.gaia import NOTIFY_EVENT, NOTIFY_OPERATION

from rpc.tool.log_tool import doctor_unread_logger
from api.tasks.notify import notify_push

# from functools import wraps
# from api.tool.user_tool import get_user_from_context
# from api.tool.user_tool import get_doctor_from_context
# from unread.noti_unread import noti_operation
# def notify(info):
#     def decorate(func):
#         @wraps(func)
#         def wrapper(*args, **kwargs):
#             func(*args, **kwargs)
#             ctx = args[0]
#             u = get_user_from_context(ctx)
#             d = get_doctor_from_context(ctx)
#             if u is not None:
#                 u = u.id
#             if d is not None:
#                 d = d.id
#             _notify(info, u, d)
#         return wrapper
#
#     return decorate


def parsed_info(info):
    """
    info = event/op
    'order/delete'
    """
    try:
        e, o = info.split('/')
        assert e in NOTIFY_EVENT
        assert o in NOTIFY_OPERATION
        return e, o
    except ValueError:
        raise Exception('Info is invalid!')
    except AssertionError:
        raise Exception('Check your event or operation!')


def send(e, o, uid, did, data):
    notify_push.delay(e, o, uid, did, data)


def notify(info, user_id=None, doctor_id=None, data=None):
    e, o = parsed_info(info)
    notify_info = u'Notify: event:<{}>, operation:<{}>, user_id:<{}>, doctor_id:<{}>, data:<{}>'.format(
        e, o, user_id, doctor_id, json.dumps(data) if data else ''
    )
    doctor_unread_logger.info(notify_info)
    send(e, o, user_id, doctor_id, data)
