#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2018/11/17

from utils.base import APIView


class TagListView(APIView):
    def get(self, request):
        offset = int(request.GET.get('offset', 1))
        limit = int(request.GET.get('limit', 10))
        filter = self.handle_filter(request.GET.get('filter', ""))
        try:
            data = self.rpc['venus/sun/tag/list'](offset=offset, limit=limit, filters=filter).unwrap()
        except Exception as e:
            raise e
        return data

    def post(self, request):
        ids = request.POST.get('ids', '').split()
        type = request.POST.get('type', '')
        updates = {}
        if type == 'offline':
            updates['is_online'] = False
        else:
            updates['is_online'] = True
        try:
            self.rpc['venus/sun/tag/batch/update'](updates=updates, ids=ids).unwrap()
        except Exception as e:
            raise e
        return {
            "message": "更新成功"
        }


class TagUpdateOrCreateView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        try:
            data = self.rpc['venus/sun/tag/get'](id=id).unwrap()
        except Exception as e:
            raise e
        if not data:
            data = {}
        else:
            pass
        return {'data': data}

    def post(self, request):
        id = request.POST.get('id')
        data = {
            'name': request.POST.get('name'),
            'description': request.POST.get('description'),
            'down_tag': list(set(request.POST.get('down_tags', '').split(','))),
            'up_tag': list(set(request.POST.get('down_tags', '').split(','))),
        }
        try:
            self.rpc['venus/sun/tag/edit'](id=id, data=data).unwrap()
        except Exception as e:
            raise e
        return {
            'message': '操作成功'
        }