# coding=utf-8
from django.contrib.auth.models import User
from django.db import models

from api.models import City, Province
from api.models import base_model
from category.models import Category
# from statistic.models import Device


class DeviceBinding(models.Model):

    user = models.ForeignKey(User, unique=True, verbose_name="关联用户")
    device = models.CharField(max_length=64, verbose_name="设备ID", blank=True, null=True)
    city = models.ForeignKey(City, blank=True, null=True, verbose_name="所在城市")
    province = models.ForeignKey(Province, blank=True, null=True, verbose_name="所在省份")
    activity_date = models.DateTimeField(auto_now=True, verbose_name="活跃日期")

    class Meta:
        app_label = 'api'
        verbose_name = "用户设备关系绑定"
        verbose_name_plural = "用户设备关系绑定"


class DeviceCategory(base_model.BaseModel):
    '''
    设备账号对应的品类
    '''
    CATEGORY_PLACE_HOLDER = '-1'
    class Meta:
        verbose_name='设备用户选择的个性品类'
        app_label = 'api'
        db_table = 'api_device_category'

    device_id = models.CharField(verbose_name='设备id', max_length=60, null=False)
    category_ids = models.CharField(verbose_name='品类id, 以逗号分隔', max_length=255, null=False)

    @classmethod
    def placeholder(cls, device_id):
        obj, _created = cls.objects.get_or_create(device_id=device_id, defaults={'category_ids': cls.CATEGORY_PLACE_HOLDER})

    @classmethod
    def create(cls, device_id, category_id_list):
        '''
        创建新的记录, 如果已经存在, 则返回成功
        '''
        category_is_valid = Category.validate_category_id(category_id_list)
        if not category_is_valid:
            return False, 'invalid category(%s)'%(','.join([str(x) for x in category_id_list]))
        try:
            category_ids = ','.join([str(x) for x in category_id_list])
            obj, _created = cls.objects.get_or_create(device_id=device_id, defaults={'category_ids':category_ids})
            if not _created and obj.category_ids == cls.CATEGORY_PLACE_HOLDER:
                obj.category_ids = category_ids
                obj.save()
            return True, obj
        except Exception as e:
            return False, e.message

    @classmethod
    def binded(cls, device_id):
        if not device_id:
            return True
        try:
            return cls.objects.filter(device_id=device_id).exists()
        except:
            return False
