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

from utils.base import APIView
from utils.time_utils import analysis_time


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


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

    def post(self, request):
        id = request.POST.get('id', '')
        creator_id = request.POST.get('creator_id')
        push_time = analysis_time(request.POST.get('push_time', 0))
        group_topic_id = request.POST.get('group_topic_id', '')
        full_url = request.POST.get('url', '') + group_topic_id

        data = {
            'url': full_url,
            'push_time': push_time,
            'icon': request.POST.get('icon', '')[:-2],
            'content': request.POST.get('content', ''),
            'title': request.POST.get('title', ''),
            'creator_id': creator_id
        }
        try:
            rep = self.rpc['venus/sun/push/edit'](id=id, data=data).unwrap()
        except Exception as e:
            raise e
        return {
            "message": '更新成功',
            "id": rep['id']
        }


class EffectPushTaskView(APIView):
    def get(self, request):
        push_task_id = request.GET.get('id')
        try:
            self.rpc['venus/sun/push/effect_push_task'](id=push_task_id).unwrap()
        except Exception as e:
            raise e
        return {
            'message': '操作成功'
        }