# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import

from api.models.user import User
from api.models import Notification, PushTask
from api.tool.user_tool import get_user_from_context
from rpc.tool.error_code import gen
from rpc.tool.error_code import CODES


def send_notification(uid, title, content="", url=""):
    try:
        user = User.objects.get(pk=uid)
    except User.DoesNotExist:
        raise gen(CODES.USER_NOT_FOUND)

    notify = Notification(user=user, title=title, content=content, url=url)
    notify.save()


def _notification_red_point(ctx, choose_id, community_id, platform):
    user = get_user_from_context(ctx)
    if not user:
        return gen(CODES.MESSAGE_UNKNOWN_USER)

    choose = False
    community = False
    if choose_id and choose_id != '0':
        task = PushTask.get_user_choose_query(user, platform).first()
        if task:
            choose = task.id != int(choose_id)
    else:
        # first = PushTask.get_user_choose_query(user, platform).first()
        # choose = (first is not None)
        choose = False

    if community_id and community_id != '0':
        task = PushTask.get_user_community_query(user, platform).first()
        if task:
            community = task.id != int(community_id)
    else:
        # first = PushTask.get_user_community_query(user, platform).first()
        # community = (first is not None)
        community = False

    return {
        'choose': choose,
        'community': community
    }
