#!/usr/bin/env python
# coding=utf-8

from rpc.decorators import bind_context
from rpc.tool.dict_mixin import to_dict
from rpc.tool.error_code import gen, CODES
from rpc.exceptions import RPCNotFoundException

from hera.queries.doctor_activity import DoctorActivityDQ
from hera.queries.doctor_activity import ActivityParticipateDQ

from hippo.tool.user_tool import get_doctor_from_context
from hippo.models import DoctorActivity, ActivityParticipate


@bind_context('doctorself/activity/list')
def doctor_activity_list(ctx, options):
    dqobj = DoctorActivityDQ()
    return dqobj.process(**options)


@bind_context('doctorself/activity/participate')
def doctor_participate(ctx, options):
    dqobj = ActivityParticipateDQ()
    return dqobj.process(**options)


@bind_context('doctorself/activity/get')
def activity_detail(ctx, activity_id, options=None):
    try:
        activity = DoctorActivity.objects.get(id=activity_id)
    except:
        raise RPCNotFoundException

    activity_data = to_dict(activity)
    activity_data['content_data'] = activity.content.content
    activity_data['title'] = activity.title
    return activity_data


@bind_context('doctorself/activity/modify')
def activity_modify(ctx, req_data):
    try:
        activity_id = int(req_data['id'])
        obj = DoctorActivity.objects.get(id=activity_id)
    except (DoctorActivity.DoesNotExist, ValueError):
        from doctor.models.content import Content
        content = Content(title=req_data['title'], content=req_data['content_data'])
        content.save()
        obj = DoctorActivity(
            content=content,
            title=req_data['title'],
            is_online=req_data['is_online'],
            begin_time=req_data['begin_time'],
            end_time=req_data['end_time'])
        obj.save()
    else:
        obj.update_req_data(req_data)
    return obj.id


@bind_context('doctor/activity/apply')
def activity_apply(ctx, activity_id):
    """医生报名参加活动
        since 2.1.0
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)
    try:
        obj = DoctorActivity.objects.get(id=activity_id)
    except DoctorActivity.DoesNotExist:
        return gen(CODES.ACTIVITY_NOT_EXIST)
    is_apply = ActivityParticipate.objects.filter(activity=obj, doctor=doctor).exists()
    if is_apply:  # 已参加过活动了
        return gen(CODES.ACTIVITY_PARTICIPATE_LIMIT)

    ap = ActivityParticipate.objects.create(
        activity=obj,
        doctor=doctor,
    )
    return ap.id
