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

import json
from utils.base import APIView


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


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

    def post(self, request):
        id = request.POST.get('id', '')
        data = {
            'name': request.POST.get('name'),
            'gender': request.POST.get('gender'),
            'city_id': request.POST.get('city'),
            'is_online': int(request.POST.get('is_online')),
            'description': request.POST.get('description'),
            'icon': request.POST.get('avatar'),
            'group_ids': list(set(json.loads(request.POST.get('group_ids', [])))),
        }
        print(json.loads(request.POST.get('group_ids', [])))
        try:
            self.rpc['venus/sun/star/edit'](id=id, data=data).unwrap()
        except Exception as e:
            raise e

        return {
            'message': '更新成功'
        }


class StarRelatedGroup(APIView):
    def get(self, request):
        id = request.GET.get('id')
        offset = int(request.GET.get('page', 0))
        count = int(request.GET.get('limit', 10))
        filters = {'star_id': id}
        try:
            data = self.rpc['venus/sun/group/list'](filters=filters, offset=(offset-1) * count, limit=count).unwrap()
        except Exception as e:
            raise e
        return data
