# coding=utf-8

import datetime

from django.db import IntegrityError
from gm_types.gaia import MULTITOPIC_REVIEW_STATUS

from rpc.tool.dict_mixin import to_dict
from rpc.exceptions import RPCNotFoundException, RPCIntegrityError, GaiaRPCFaultException
from rpc.decorators import bind_context
from rpc.tool.log_tool import info_logger

from ..queries.multitopic import MultitopicDQ, ZonewhitelistDQ, MultitopicreviewDQ

from api.models.multitopic import MultiTopic, ZoneWhiteList, MultiTopicReview
from api.tasks.multitopic_task import add_multitopic_review


multitopic_pre = 'hera/multitopic'
zonewhitelist_pre = 'hera/zonewhitelist'
multitopicreview_pre = 'hera/multitopicreview'


@bind_context(multitopic_pre + '/query')
def multitopic_query(ctx, options):
    dqobj = MultitopicDQ()
    return dqobj.process(**options)


@bind_context(multitopic_pre + '/get_visible')
def get_multitopic_visible(ctx):
    visible = MultiTopic.get_visible()
    return {'visible': visible['multitopic']}


@bind_context(multitopic_pre + '/set_visible')
def set_multitopic_visible(ctx, visible=True):
    MultiTopic.set_visible(visible=visible)


@bind_context(multitopic_pre + '/get')
def multitopic_detail(ctx, multitopic_id, options=None):
    try:
        multitopic = MultiTopic.objects.get(id=multitopic_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    data = to_dict(multitopic, **options)
    return data


@bind_context(multitopic_pre + '/edit')
def multitopic_edit(ctx, multitopic_id=None, multitopic_info=None):
    if multitopic_info is None:
        return None

    for key in ['diary_id', 'topic_id', 'activity_id', 'zhiboconfig_id', 'question_id']:
        multitopic_info[key] = multitopic_info.pop(key) or None
    multitopic_info['service_id'] = multitopic_info.pop('service')
    multitopic_info['tag_id'] = multitopic_info.pop('tag')
    multitopic_info['special_id'] = multitopic_info.pop('special')

    if multitopic_id is None:
        try:
            multitopic = MultiTopic.objects.create(**multitopic_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            multitopic = MultiTopic.objects.get(id=multitopic_id)
            for k, v in multitopic_info.iteritems():
                setattr(multitopic, k, v)
            multitopic.save()
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException

    return multitopic.id


@bind_context(multitopic_pre + '/listupdate')
def multitopic_listupdate(ctx, items):
    info = []
    for obj in items:
        multitopic = MultiTopic.objects.get(pk=obj['key'])
        multitopic.is_online = obj['is_online']
        multitopic.ordering = obj['rank']
        multitopic.save()
        info.append(obj['key'])
    return info


@bind_context(zonewhitelist_pre + '/query')
def zonewhitelist_query(ctx, options):
    dqobj = ZonewhitelistDQ()
    return dqobj.process(**options)


@bind_context(zonewhitelist_pre + '/get')
def zonewhitelist_detail(ctx, zonewhitelist_id=None, options=None):
    try:
        zonewhitelist = ZoneWhiteList.objects.get(id=zonewhitelist_id)
    except:
        raise RPCNotFoundException
    data = {}
    data['id'] = zonewhitelist.id
    data['zone_id'] = zonewhitelist.zone_id
    data['is_online'] = zonewhitelist.is_online
    return data


@bind_context(zonewhitelist_pre + '/edit')
def zonewhitelist_edit(ctx, zonewhitelist_id=None, zonewhitelist_info=None):
    if zonewhitelist_info is None:
        return None
    if zonewhitelist_id is None:
        zone_id = zonewhitelist_info['zone_id']
        if ZoneWhiteList.objects.filter(zone_id=zone_id):
            message = u'该圈子已在白名单'
            raise GaiaRPCFaultException(error=1, message=message, data=None)
        zonewhitelist = ZoneWhiteList.objects.create(**zonewhitelist_info)
        today = datetime.datetime.now()
        bt = today - datetime.timedelta(days=30)
        add_multitopic_review.delay(zone_id=zonewhitelist.id, bt=bt)
    else:
        try:
            zonewhitelist = ZoneWhiteList.objects.get(id=zonewhitelist_id)
            for k, v in zonewhitelist_info.iteritems():
                setattr(zonewhitelist, k, v)
            zonewhitelist.save()
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException

    return zonewhitelist.id


@bind_context(multitopicreview_pre + '/query')
def multitopicreview_query(ctx, options):
    dqobj = MultitopicreviewDQ()
    return dqobj.process(**options)


@bind_context(multitopicreview_pre + '/update')
def multitopic_update(ctx, items, action):
    mtr = MultiTopicReview.objects.filter(id__in=items)

    if action == 'waiting':
        mtr.update(status=MULTITOPIC_REVIEW_STATUS.WAITTING)

    elif action == 'pass':
        mtr.update(status=MULTITOPIC_REVIEW_STATUS.PASS)

    elif action == 'reject':
        mtr.update(status=MULTITOPIC_REVIEW_STATUS.REJECT)

    return {'message': 'success'}
