# coding: utf-8

import datetime

from django.conf import settings
from django.db import transaction
from gm_types.gaia import DIARY_ORDER_TYPE, DIARY_OPERATE
from gm_types.gaia import MEMBERSHIP_LEVEL

from social.models import SocialInfo
from talos.libs.datetime_utils import (
    get_humanize_datetime,
    get_timestamp_or_none
)
from talos.libs.image_utils import get_full_path
from talos.models.diary import Diary
from talos.services import UserService
from talos.tools.user_tool import (
    get_auth_type_by_userid,
)
from utils.rpc import rpc_client
from .es_helpers import get_objects_from_queryset_and_pk_list


def get_diary_by_id(diary_id):
    """
    NOTE:
        根据diary_id获取diary信息
    :return:
    """
    try:
        diary = Diary.objects.get(id=diary_id)
        return diary
    except Diary.DoesNotExist:
        return None


def get_diary_info_for_index(diary_ids, user):
    if not diary_ids:
        return []

    diaries = get_objects_from_queryset_and_pk_list(
        Diary.objects.all().prefetch_related("topics"),
        diary_ids,
    )
    result = []
    user_ids = [d.user_id for d in diaries if d.user_id]
    diary_author_dict = UserService.get_users_by_user_ids(user_ids)

    social_info = None
    if user:
        social_info = SocialInfo(uid=user.id)

    for diary in diaries:
        cover = diary.cover
        if not cover:
            continue

        latest_topic = diary.latest_topic
        title = latest_topic.title if latest_topic else ''
        content = latest_topic.answer if latest_topic else ''

        diary_author = diary_author_dict.get(diary.user_id)

        # TODO: use diary.get_diary_info
        diary_data = {
            'title_style_type': diary.title_style_type,
            'title': title,
            'content': content,
            'diary_id': diary.id,
            'diary_num': diary.diary_num,
            # 'city': get_city_name_by_user(diary.user),
            'user_id': diary.user.id,
            'user_portrait': diary_author and diary_author.portrait or '',
            'user_nickname': diary_author and diary_author.nickname or '',
            'author_type': get_auth_type_by_userid(diary.user.id),
            'date': get_humanize_datetime(diary.last_modified),
            'last_modified': get_timestamp_or_none(diary.last_modified),
            'reply_num': diary.reply_num,
            'vote_num': diary.vote_num,
            'tags': diary.tags_new_era,
            'images': cover,
            'view_num': diary.view_num,
            'is_voted': diary.is_voted_by(user),
            'is_following': social_info and social_info.is_following_user(uid=diary.user.id) or False,
            'latest_topic_id': latest_topic and latest_topic.id or 0,
            'membership_level': diary_author and diary_author.membership_level or MEMBERSHIP_LEVEL.NORMAL,
            'author': {
                'vote_num_gained': diary_author and diary_author.vote_count,
                'topic_num_posted': diary_author and diary_author.topic_count,
            },
            'is_online': diary.is_online,
        }
        result.append(diary_data)
    return result


def get_diaries_by_tags(tag_ids, offset=0, size=10,
                        sort_type=DIARY_ORDER_TYPE.HOT):
    filters = {'tag_ids': tag_ids}
    diaries_info = rpc_client['api/diary/filter_diary'](
        offset=offset, size=size, sort_type=sort_type, filters=filters
    ).unwrap()
    ids = diaries_info['diary_ids']
    diaries = get_objects_from_queryset_and_pk_list(
        Diary.objects.filter(is_online=True), pk_list=ids
    )

    def diary_content(diary):
        latest_topic = diary.topics.filter(flag='n', is_online=True).last()
        content = latest_topic.answer if latest_topic else ''
        return content

    diaries = [
        {
            'diary_id': diary.id,
            'diary_cover': (
                diary.post_operation_image
                if diary.post_operation_image
                else diary.newest_cover()
            ),
            'diary_vote_num': diary.vote_num,
            'content': diary_content(diary),
            'tags': diary.tags_new_era,
            'images': diary.cover,

        } for diary in diaries
    ]
    return diaries


def clean_video_url(video_url):
    return video_url.replace(settings.VIDEO_HOST, '')


def set_diary_cover(cover, diary):
    if cover:
        with transaction.atomic():
            cover = get_full_path(cover)
            pre_images = diary.pre_operation_images.all()
            for image in pre_images:
                if image.image_url == cover or image.cover_image_url == cover:
                    image.is_cover = True
                else:
                    image.is_cover = False
                image.save()


def set_pre_operation_images(pre_operation_images, cover, diary):
    if pre_operation_images:
        taken_time = datetime.datetime.now()
        has_cover = False
        for image in pre_operation_images:
            if not image.get('image', ''):
                break

            if has_cover:
                is_cover = False
            else:
                is_cover = False if image['image'] != cover else True

            if is_cover:
                has_cover = True

            diary.pre_operation_images.create(
                image_url=image['image'], taken_time=taken_time,
                is_cover=is_cover, cover_image_url=image.get('modified_image_url'))
            # 记录操作 UPDATE_INFO
            diary.set_diary_operate(DIARY_OPERATE.UPDATE_INFO)


def set_pre_operation_images_v1(pre_operation_images, cover, diary):
    if pre_operation_images:
        diary.pre_operation_images.clear()
        set_pre_operation_images(pre_operation_images, cover, diary)

