# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

from django.db import models

from talos.services.user import UserService

from .topic import Problem


class ProblemFavor(models.Model):
    class Meta:
        unique_together = ("user_id", "problem")
        app_label = 'talos'
        db_table = 'api_problemfavor'

    user_id = models.IntegerField(help_text=u'收藏的用户外键id')
    problem = models.ForeignKey(Problem, related_name="favor_problem", help_text=u"收藏的问题")
    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"是否已读")

    @property
    def user(self):
        return UserService.get_user_by_user_id(self.user_id)

    @classmethod
    def list_by_ids(cls, ids):

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

    @classmethod
    def list_unread(cls, user_id):

        problem_ids = list(Problem.objects.filter(is_online=True, user_id=user_id).values_list('id', flat=True))
        return ProblemFavor.objects.filter(
            is_deleted=False, unread=True, problem_id__in=problem_ids
        )

    @classmethod
    def get_favor_count(cls, user_id):
        pro_ids = list(ProblemFavor.objects.filter(
            user_id=user_id, is_deleted=False).values_list('problem_id', flat=True))
        return Problem.objects.filter(id__in=pro_ids, is_online=True).count()
