# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

from gm_rpcd.all import bind

from talos.models.diary import Diary
from talos.models.topic import TopicImage
from talos.libs.image_utils import get_full_path
from talos.manager.diary import diary_list_manager
from talos.services import GoodsService
from talos.rpc import CODES, gen


@bind("diary/journey/list")
def get_journey_list(diary_ids):
    diarys = diary_list_manager.get_diary_list_by_diary_ids_for_journey(ids=diary_ids)
    service_ids = []
    for diary in diarys:
        service_ids.append(diary['service_id'])

    services = GoodsService.get_service_project_tags_by_ids(service_ids)
    for diary in diarys:
        service = services.get(diary["service_id"])
        if not service:
            continue
        diary["tag"] = service["tag"]
    return diarys


@bind('diary/journey/cover')
def get_journey_diary_cover(diary_id):
    try:
        diary = Diary.objects.get(id=diary_id)
    except Diary.DoesNotExist:
        return gen(CODES.DIARY_NOT_FOUND)

    cover = diary.cover
    return {
        "before": get_full_path(cover[0]["image"], '-half') if cover else '',
        "after": get_full_path(cover[1]["image"], '-half') if len(cover) > 1 else ''
    }


@bind('diary/journey/image_list')
def get_journey_diary_image_list(diary_id):
    diary = Diary.objects.get(id=diary_id)
    topic_ids = list(diary.topics.all().values_list('id', flat=True))
    images = TopicImage.objects.filter(topic_id__in=topic_ids).order_by('-id')[0:21]
    result = []
    for image in images:
        result.append(get_full_path(image.image_url, '-half'))
    return result
