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

from rpc.decorators import bind, cache_page
from rpc.tool.dict_mixin import to_dict
from rpc.tool.error_code import gen
from rpc.tool.error_code import CODES

from api.models import BodyPart
from api.models import BodyPartSubItem


@bind('api/bodypart/all')
@bind("api/bodypart/list")
@cache_page(120)
def get_all_bodyparts():
    body_parts = BodyPart.objects.filter(is_deleted=False).order_by('rank')
    return [bp.item_data() for bp in body_parts]


@bind("api/tags")
@bind("api/bodypart/list_as_tag")
@cache_page(120)
def get_all_tags():
    result = []
    body_parts = BodyPart.objects.filter(is_deleted=False).order_by('rank', 'id')
    for body_part in body_parts.all():
        tags = [sub_item.tag_data() for sub_item in body_part.sub_items.filter(is_deleted=False).order_by('rank')]
        item = body_part.item_data()
        item[u'tags'] = tags
        result.append(item)
    return result


@bind('api/bodypart/by_id')
def bodypart_by_id(id):
    model = BodyPart
    try:
        m = model.objects.get(id=id)
        if hasattr(m, 'to_dict'):
            return m.to_dict()
        else:
            return to_dict(m)
    except model.DoesNotExist:
        return gen(CODES.BODYPART_NOT_FOUND)


@bind('api/bodypart_subitem/by_id')
def bodypart_subitem_by_id(id):
    model = BodyPartSubItem
    try:
        m = model.objects.get(id=id)
        if hasattr(m, 'to_dict'):
            return m.to_dict()
        else:
            return to_dict(m)
    except model.DoesNotExist:
        return gen(CODES.BODYPART_SUBITEM_NOT_FOUND)
