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

from community.models import TopicSticky

from rpc.decorators import bind_context
from rpc.exceptions import RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from hera.utils import model_edit
from hera.queries.topicsticky import TopicStickyDQ


uri_pre = 'hera/communitysticky'


@bind_context(uri_pre+'/get')
def sticky_get(ctx, sticky_id, options=None):
    try:
        sticky = TopicSticky.objects.get(id=sticky_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    sticky_data = to_dict(sticky, **options)
    return sticky_data


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


@bind_context(uri_pre+'/edit')
def sticky_edit(ctx, sticky_id=None, sticky_info=None):
    if sticky_info is None:
        return None

    sticky = model_edit(TopicSticky, sticky_id, sticky_info)
    return {'id': sticky.id}


@bind_context(uri_pre + '/update')
def update_topic_status(ctx, sticky_id):
    try:
        sticky = TopicSticky.objects.get(id=sticky_id)
    except TopicSticky.DoesNotExist:
        raise RPCNotFoundException
    sticky.is_online = not sticky.is_online
    sticky.save()
    return sticky.id
