# coding=utf-8
import threading
from urlparse import urljoin

from django.conf import settings
from django.contrib.auth.signals import user_logged_in
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from gm_types.gaia import RED_PACKET, TRANS_ACTION, TRANS_EVENT, TRANS_STATUS
from gm_types.push import PUSH_INFO_TYPE
from gm_protocol import GmProtocol

from api.tool.push_tool import NotifyManager
from api.tool.notification_tool import send_notification
from cashback.models import Registration, TransactionLog, TransactionRemark, Dialog, UserBalance

# todo 功能下线了，代码确认后可以删掉
@receiver(user_logged_in)
def user_post_login(sender, user, request, **kwargs):
    """
    usr post login signal.
    :param sender:
    :param user:
    :param request:
    :param kwargs:
    :return:
    """
    protocol = GmProtocol()
    try:
        registration = Registration.objects.get(invitee=user, activated=False)
    except Registration.DoesNotExist:
        return False

    packet = Dialog.objects.get(type=RED_PACKET.INVITE).packet
    with threading.Lock():
        registration.activated = True
        registration.login_time = timezone.now()
        registration.save()

        remark = TransactionRemark.objects.create(event_type=TRANS_EVENT.INVITE_PACKET,
                                                  registration_id=registration.id,
                                                  packet_id=packet.id)

        TransactionLog.objects.create(user=registration.inviter,
                                      amount=packet.amount,
                                      type=TRANS_ACTION.DEPOSIT,
                                      state=TRANS_STATUS.PASS,
                                      remark=remark)

    url = urljoin(settings.BACKEND_API_HOST, '/hybrid/cashback/transaction')
    # send push
    NotifyManager.send_push(registration.inviter_id, alert=u"邀请新用户成功，现金奖励已发放，点击查看",
                            extra={
                                "type": PUSH_INFO_TYPE.GM_PROTOCOL,
                                "pushUrl": protocol.get_webview(url=url)
                            })
    # send notification
    phone = registration.invitee.person.phone
    phone = phone[:3] + "****" + phone[8:]
    msg = "恭喜您邀请用户{phone}成功，现金奖励红包已发到您的余额账户啦～点击查看赚了多少".format(phone=phone)
    send_notification(registration.inviter_id, "邀请成功", content=msg, url=protocol.get_webview(url=url))
    return True


@receiver(post_save, sender=TransactionLog)
def transaction_log_post_save(sender=None, instance=None, created=True, **kwargs):
    """

    :param sender:
    :param instance:
    :param created:
    :param kwargs:
    :return:
    """
    if created:
        try:
            UserBalance.objects.create(user=instance.user, join_time=timezone.now())
        except:
            pass
