# coding=utf-8
from django.db import IntegrityError

from api.models.icon import Icon
from rpc.decorators import bind, bind_context
from rpc.exceptions import RPCIntegrityError
from rpc.tool.dict_mixin import to_dict


@bind('api/hera/icon/edit')
def icon_edit(icon_info, icon_id=None):
    """
    icon 编辑
    :param icon_info:
    :param icon_id:
    :return:
    """
    result = {
        'error': 0,
        'message': '创建成功',
        'data': ''
    }
    order = icon_info.pop('order', 9999)

    if not icon_id:
        try:
            icon = Icon.objects.create(**icon_info)
        except IntegrityError:
            raise RPCIntegrityError(message='名称和索引不能重复')
    else:
        icon = Icon.objects.get(id=icon_id)
        try:
            for key, value in icon_info.items():
                setattr(icon, key, value)
            icon.save()
        except IntegrityError:
            result['error'] = -1
            result['message'] = '名称不能重复'
            result['data'] = icon.id
            return result

        icon.to(order)
    result['data'] = icon.id

    return result


@bind('api/hera/icon/detail')
def get_icon_detail(icon_id):
    """
    icon 详情
    :param icon_id:
    :return:
    """
    result = {
        'error': 0,
        'message': '',
        'data': []
    }
    try:
        icon = Icon.objects.get(id=icon_id)
    except Icon.DoesNotExist:
        result['error'] = 1404
        return result

    result['data'] = to_dict(icon)

    return result


@bind('api/hera/icon/list')
def get_icon_list(offset=0, count=10):
    """
    icon 列表
    :return:
    """
    result = {
        'error': 0,
        'message': '',
        'data': []
    }
    data = []
    icons = Icon.objects.all().order_by('order')[offset: offset+count]
    for icon in icons:
        data.append(icon.to_dict())
    result['data'] = data

    return result


@bind('api/hera/order/list')
def get_all_order():
    """
    获取icon所有的order值，用于hera后台修改排序
    :return:
    """
    orders = list(Icon.objects.all().order_by('order').values_list('order'))
    return {
        'orders': orders
    }
