# -*- coding: UTF-8 -*-

from rpc.decorators import bind_context
from rpc.exceptions import (RPCPermissionDeniedException, RPCIntegrityError,
    RPCNotFoundException)
from rpc.tool.dict_mixin import to_dict
from statistic.models import Device
from ..utils import remote_choices
from ..datatables import DeviceDT

from rpc.tool.log_tool import info_logger
from api.models.others import UserBlackList
from api.models.user import User

uri_pre = 'hera/device'


@bind_context(uri_pre+'/choices')
def device_choices(ctx, q='', page=1, num=30, initial=None):
    src_map = {'id': 'id', 'text': 'name'}
    if initial is None:
        qry_item = {'key': 'name', 'val': q}
        fetch_seleted = False
    else:
        qry_item = {'key': 'id', 'val': initial}
        fetch_seleted = True
    return remote_choices(Device, qry_item, fetch_seleted, page, num, src_map)


@bind_context(uri_pre+'/list')
def device_datatable(ctx, req_data):
    dtobj = DeviceDT(Device)
    return dtobj.process(req_data)


@bind_context(uri_pre+'/get')
def device_detail(ctx, device_id, options=None):
    try:
        device = Device.objects.get(id=device_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    device_data = to_dict(device, **options)
    device_data['blacklist'] = False if device.userblacklist_set.count() == 0 else True
    usernum = {}
    for user_id in device_data['user']:
        user = User.objects.get(id=user_id)
        usernum[user.id] = user.last_name
    device_data['user_num'] = usernum
    return device_data


@bind_context(uri_pre+'/edit')
def device_edit(ctx, device_id=None, device_info=None):
    if device_info is None:
        return None

    if device_id is None:
        try:
            device = Device.objects.create(**device_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            device = Device.objects.get(id=device_id)
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
        for k, v in device_info.iteritems():
            setattr(device, k, v)
        device.save()
    return device.id


@bind_context(uri_pre+'/black')
def device_black(ctx, items):
    info = []
    for obj in items:
        if obj['is_black']:
            UserBlackList.objects.get_or_create(device_id=obj['key'])
        else:
            UserBlackList.objects.filter(device_id=obj['key']).delete()
        info.append(obj['key'])
    return info
