# 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.libs.image_utils import get_full_path
from talos.libs.datetime_utils import get_timestamp_or_none
from talos.services.user import UserService

from .diary import Diary


class DiaryVote(models.Model):
    """
        赞日记本
    """

    class Meta:
        verbose_name = u'赞日记本'
        verbose_name_plural = u'赞日记本'
        unique_together = ('user_id', 'diary')
        db_table = 'api_diaryvote'
        app_label = 'talos'

    user_id = models.IntegerField(verbose_name=u'用户外键id')
    diary = models.ForeignKey(Diary, related_name="diary_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"是否机器人点赞")

    def to_dict(self):
        latest_topic = self.diary.latest_topic
        if latest_topic:
            content = latest_topic.answer or latest_topic.ask or latest_topic.title or ''
        else:
            content = ''

        images = self.diary.cover

        user = UserService.get_user_by_user_id(self.user_id)
        data = {
            'diary_id': self.diary_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'], '-thumb') or '',
            'content': escape(content),
            'type': VOTEOBJECT.DIARY,
            'portrait': user.portrait,
            'membership_level': user.membership_level,
        }

        return data
