# coding: utf-8
from __future__ import unicode_literals, absolute_import, print_function

import datetime

from api.models import IndustryNews
from rpc.decorators import bind
from rpc.tool.error_code import gen, CODES


@bind('api/news/list')
def get_industry_news(count=3):
    result = {'news': []}
    now = datetime.datetime.now()
    news = IndustryNews.objects.filter(
        is_online=True, begin_time__lte=now,
        end_time__gte=now
    ).order_by('-ordering', '-begin_time')
    if news:
        result['news'] = [{'title': new.title, 'id': new.id}
                          for new in news[:count]]
    return result


@bind('api/news/info')
def get_industry_news_detail(news_id):
    try:
        news = IndustryNews.objects.get(pk=news_id)
    except IndustryNews.DoesNotExist:
        return gen(CODES.NEWS_NOT_FOUND)
    return {
        'id': news.id,
        'title': news.title,
        'content': news.content,
    }

