# encoding=utf-8

import datetime
from django.db.models import Q
from django.db import IntegrityError
from rpc.decorators import bind_context
from rpc.exceptions import RPCIntegrityError, RPCNotFoundException
from rpc.tool.log_tool import logging_exception
from api.models import WaterMark, WaterMarkService
from api.models import Service


uri_pre = 'hera/watermark'


@bind_context(uri_pre + '/edit')
def watermark_edit(ctx, watermark_id=None, watermark_info=None):
    if watermark_id is None:
        try:
            watermark = WaterMark.objects.create(**watermark_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            watermark = WaterMark.objects.get(id=watermark_id)
        except:
            logging_exception()
            raise RPCNotFoundException
        for k, v in watermark_info.iteritems():
            setattr(watermark, k, v)
        watermark.save()
    return {
        'id': watermark.id
    }


@bind_context(uri_pre + '/service/delete')
def watermark_service_delete(ctx, watermark_service_id):
    WaterMarkService.objects.get(id=watermark_service_id).delete()


@bind_context(uri_pre + '/service/delete_all')
def watermark_service_delete(ctx, watermark_id):
    WaterMarkService.objects.filter(watermark_id=watermark_id).delete()


@bind_context(uri_pre + '/service/add/')
def watermark_service_delete(ctx, add_type, add_ids):
    if add_type == 'special':
        q = Q(specialitem__special_id__in=add_ids)
    elif add_type == 'service':
        q = Q(id__in=add_ids)
    return [
        {
            'id': service.id,
            'name': service.name,
        }for service in Service.objects.filter(q).distinct()
    ]


@bind_context(uri_pre + '/service/save/')
def watermark_service_delete(ctx, watermark_id, save_ids):
    watermark = WaterMark.objects.get(id=watermark_id)
    old_services = set(watermark.services.values_list('id', flat=True))
    new_services = set(map(int, save_ids))
    print new_services
    print old_services
    print list(new_services - old_services)
    WaterMarkService.objects.bulk_create(
        [
            WaterMarkService(
                watermark_id=watermark_id,
                service_id=service_id
            ) for service_id in list(new_services - old_services)
        ]
    )
