# -*- coding: UTF-8 -*-

import json
from rpc.decorators import bind_context
from ..queries.servicecomment import ServiceCommentDQ
from rpc.exceptions import RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from api.models import ServiceComment, ServiceCommentImage

uri_pre = 'hera/servicecomment'


@bind_context(uri_pre + '/query')
def servicecomment_query(ctx, options):
    dqobj = ServiceCommentDQ()
    return dqobj.process(**options)


@bind_context(uri_pre + '/listupdate')
def servicecomment_listupdate(ctx, items):
    ids = []
    is_online = None
    for item in items:
        comment = ServiceComment.objects.get(id=item['key'])
        comment.is_online = item['is_online']
        comment.save()
        ids.append(comment.id)
        is_online = item['is_online']
    return {
        'ids': ids,
        'is_online': is_online
    }


@bind_context(uri_pre + '/get')
def servicecomment_detail(ctx, comment_id):
    try:
        comment = ServiceComment.objects.get(id=comment_id)
    except:
        raise RPCNotFoundException

    comment_data = to_dict(comment)
    comment_data['user_id'] = comment.order.user_id
    comment_data['user_name'] = comment.order.user.last_name
    comment_data['service_name'] = comment.service.name
    comment_data['doctor_id'] = comment.service.doctor_id
    comment_data['doctor_name'] = comment.service.doctor.name
    comment_data['hospital_id'] = comment.service.doctor.hospital_id
    comment_data['hospital_name'] = comment.service.doctor.hospital.name if comment_data['hospital_id'] else ''
    comment_data['images'] = list(comment.image.values_list('image', flat=True))
    comment_data['create_time'] = str(comment.create_time).split('.')[0]
    return comment_data


@bind_context(uri_pre + '/edit')
def servicecomment_edit(ctx, comment_id, comment_info):
    try:
        comment = ServiceComment.objects.get(id=comment_id)
    except:
        raise RPCNotFoundException
    images = comment_info.pop('images')
    for k, v in comment_info.iteritems():
        setattr(comment, k, v)
    comment.save()

    new_images = set(images)
    old_images = set(comment.image.values_list('image', flat=True))
    for image in (new_images - old_images):
        ServiceCommentImage.objects.get_or_create(service_comment_id=comment.id, image=image)
    ServiceCommentImage.objects.filter(service_comment_id=comment.id, image__in=(old_images - new_images)).delete()
