# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

from django.db import models
from django.conf import settings

from talos.models.diary.diary import Diary


class DiaryFavor(models.Model):
    class Meta:
        unique_together = ('user_id', 'diary')
        verbose_name = '日记本收藏'
        app_label = 'talos'
        db_table = 'api_diaryfavor'

    user_id = models.IntegerField(help_text=u'收藏者外键id')
    diary = models.ForeignKey(Diary, related_name='favor_diary_diary', help_text='收藏的日记本')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u"收藏时间")
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)
    is_deleted = models.BooleanField(default=False, help_text=u"是否已经删除")
    unread = models.BooleanField(default=True, help_text=u"是否已读")

    @classmethod
    def list_by_ids(cls, ids):

        return DiaryFavor.objects.filter(is_deleted=False, pk__in=ids)

    @classmethod
    def list_unread(cls, user_id):

        diary_ids = list(Diary.objects.using(settings.SLAVE_DB_NAME).filter(
            is_online=True, user_id=user_id).values_list('id', flat=True))
        if not diary_ids:
            return 0

        return DiaryFavor.objects.filter(
            is_deleted=False, unread=True, diary_id__in=diary_ids
        )

    @classmethod
    def get_favor_count(cls, user_id):
        diary_ids = list(DiaryFavor.objects.using(settings.SLAVE_DB_NAME).filter(
            user_id=user_id, is_deleted=False).values_list('diary_id', flat=True))
        return Diary.objects.using(settings.SLAVE_DB_NAME).filter(id__in=diary_ids, is_online=True).count()