# coding=utf-8
from __future__ import absolute_import


from django.db import IntegrityError

from rpc.decorators import bind_context
from rpc.exceptions import RPCIntegrityError, RPCNotFoundException
from rpc.tool.log_tool import info_logger
from talos.models.topic import Problem, TopicImage
from talos.models.topic.column import Article

uri_pre = 'hera/suozhang/topic'


@bind_context(uri_pre + '/images')
def topic_images(ctx, topic_id):
    images = []
    try:
        topic_images = TopicImage.objects.filter(topic_id=topic_id)
        for image in topic_images:
            images.append(image.image_url)
    except:
        pass

    return images


@bind_context(uri_pre + '/edit')
def topic_edit(ctx, topic_id=None, topic_info=None):
    if topic_info is None:
        return None
    tags = topic_info.pop('tags', [])
    images = topic_info.pop('images', [])

    if topic_id is None:
        try:
            topic_info['user_id'] = 22
            topic = Problem.objects.create(**topic_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            topic = Problem.objects.get(id=topic_id)
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
        for k, v in topic_info.iteritems():
            setattr(topic, k, v)
        topic.save()

    if tags:
        topic.upd_tags(tags)

    if topic.user.id == 22:
        TopicImage.objects.filter(topic_id=topic.id).delete()
        for image_url in images:
            if image_url:
                topic_image = TopicImage(topic=topic, image_url=image_url)
                topic_image.save()

    return topic.id


@bind_context(uri_pre + '/listupdate')
def topic_listupdate(ctx, items):
    info = []
    for obj in items:
        problem = Problem.objects.get(pk=obj['key'])
        Article.objects.filter(article_id=obj['key']).update(is_online=obj['is_online'])
        problem.is_online = obj['is_online']
        problem.save()
        info.append(obj['key'])
    return info
