# coding=utf-8
from hera.queries.upload_button import UploadButtonDQ
from rpc.decorators import bind_context
from api.models import UploadButton
from django.db import IntegrityError
from django.db import transaction
from django.db.models import Q
from rpc.exceptions import RPCIntegrityError, RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
uri_pre = 'hera/uploadbutton'


@bind_context(uri_pre + '/query')
def upload_button_query(ctx, options):
    dqobj = UploadButtonDQ()
    return dqobj.process(**options)


@bind_context(uri_pre + '/get')
def upload_button_get(ctx, upload_button_id):
    """
    获取上传button根据id
    """
    if upload_button_id is None:
        return None
    try:
        upload_button = UploadButton.objects.get(id=upload_button_id)
    except IntegrityError:
        raise RPCIntegrityError
    upload_button_data = to_dict(upload_button)
    return upload_button_data


@bind_context(uri_pre + '/edit')
@transaction.atomic
def upload_button_edit(ctx, upload_button_id=None, upload_button_info=None):
    if upload_button_info is None:
        return None
    filter_collection = UploadButton.objects.filter(
        Q(end_show_time__range=(upload_button_info['start_show_time'], upload_button_info['end_show_time'])) |
        Q(start_show_time__range=(upload_button_info['start_show_time'], upload_button_info['end_show_time'])) |
        Q(Q(end_show_time__gte=upload_button_info['end_show_time']) &
          Q(start_show_time__lte=upload_button_info['start_show_time']))
    ).exclude(id=upload_button_id)
    if filter_collection:
        return None
    if upload_button_id is None:
        try:
            upload_button = UploadButton.objects.create(**upload_button_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            upload_button = UploadButton.objects.get(id=upload_button_id)
            for k, v in upload_button_info.iteritems():
                setattr(upload_button, k, v)
            upload_button.save()
        except:
            raise RPCNotFoundException

    return upload_button.id
