# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

from django.db import models
from django.utils.html import escape

from gm_types.gaia import VOTEOBJECT

from talos.services.user import UserService
from talos.libs.image_utils import get_full_path
from talos.libs.datetime_utils import get_timestamp_or_none

from .topic import Problem
from .topicimage import TopicImage


class TopicVote(models.Model):
    """
        赞话题
    """

    class Meta:
        verbose_name = u'赞话题'
        verbose_name_plural = u'赞话题'
        unique_together = ('user_id', 'topic')
        db_table = 'api_topicvote'
        app_label = 'talos'

    user_id = models.IntegerField(verbose_name=u'用户外键id')
    topic = models.ForeignKey(Problem, related_name="votes")
    vote_time = models.DateTimeField(auto_now_add=True, verbose_name=u"点赞时间")
    unread = models.BooleanField(default=True)
    is_fake = models.BooleanField(default=False, verbose_name=u"是否机器人点赞")

    topic_author_id = models.IntegerField(verbose_name=u'帖子用户外键id', db_index=True, default=None)

    def to_dict(self):
        content = self.topic.get_title()
        images = TopicImage.objects.filter(topic=self.topic).order_by('id')

        if self.topic.diary:
            topic_type = VOTEOBJECT.DIARY
        else:
            topic_type = VOTEOBJECT.TOPIC

        user = UserService.get_user_by_user_id(user_id=self.user_id)
        data = {
            'topic_id': self.topic_id,
            'nickname': user.nickname,
            'user_id': self.user_id,
            'vote_time': get_timestamp_or_none(self.vote_time),
            'image': images and get_full_path(images[0].image_url, '-thumb') or '',
            'content': escape(content),
            'membership_level': user.membership_level,
            'type': topic_type,
            'portrait': user.portrait,
        }
        return data

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