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

from django.db import models
from .user import User
from .area import City


class JpushBindUser(models.Model):
    class Meta:
        verbose_name = u'极光绑定用户关系'
        verbose_name_plural = u'极光绑定用户关系'
        app_label = 'api'

    user = models.ForeignKey(User)
    registration_id = models.CharField(max_length=100, verbose_name=u'jpush-id', db_index=True)

    def store(self, *args, **kwargs):
        try:
            object = JpushBindUser.objects.get(registration_id=self.registration_id)
            object.user = self.user
            object.save()
        except JpushBindUser.DoesNotExist:
            JpushBindUser.objects.create(user=self.user, registration_id=self.registration_id)


class JpushAnonymousBindUser(models.Model):
    class Meta:
        verbose_name = u'极光匿名用户绑定'
        app_label = 'api'

    registration_id = models.CharField(max_length=64, verbose_name=u'jpush-id', unique=True)
    city = models.ForeignKey(City, null=True, default=None, db_index=True)

    @classmethod
    def save_by_city(cls, registration_id, city=None):
        binding, created = cls.objects.update_or_create(
            registration_id=registration_id,
            defaults={'city': city})
