# coding=utf-8

from django.db import models
from django.utils import timezone

from apps.customer.models import Customer
from apps.commodity.models import Commodity


class Collection(models.Model):

    customer = models.ForeignKey(Customer, verbose_name=u'收藏人', on_delete=models.PROTECT)
    commodity = models.ForeignKey(Commodity, verbose_name=u'收藏商品', on_delete=models.PROTECT)
    create_time = models.DateTimeField(verbose_name=u'收藏时间', default=timezone.now, editable=False)
    delete = models.BooleanField(verbose_name=u'删除', default=False, editable=False)

    class Meta:
        db_table = "collection"
        verbose_name = u'收藏'
        ordering = ['-id']
        default_permissions = ()

    @staticmethod
    def is_collection(customer, commodity):
        count = Collection.objects.filter(customer=customer, commodity=commodity, delete=False).count()
        return count != 0

    @staticmethod
    def addnew(customer, commodity):
        instance = Collection.objects.filter(customer=customer, commodity=commodity).first()
        if instance:
            instance.delete = False
            instance.create_time = timezone.now()
            instance.save()
        else:
            instance = Collection.objects.create(customer=customer, commodity=commodity, create_time=timezone.now())
        return instance
