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

from utils.base import APIView
from utils.time_utils import utc_to_datetime, datetime_toString, unix_time_to_datetime, 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/community/push/sun_list'](offset=page, 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/community/push/get'](id=id).unwrap()
        except Exception as e:
            raise e
        return {'data': data}

    def post(self, request):
        id = request.POST.get('id', '')
        try:
            push_time = unix_time_to_datetime(int(request.POST.get('push_time', 0)) / 1000)
        except ValueError:
            push_time = utc_to_datetime(request.POST.get('push_time', '')[:-5] + 'Z')
        data = {
            'url': request.POST.get('url', ''),
            'push_time': push_time,
            'icon': request.POST.get('icon', '')[:-2],
            'content': request.POST.get('content', ''),
            'title': request.POST.get('title', ''),
        }
        try:
            self.rpc['venus/community/push/update_or_create'](id=id, data=data).unwrap()
        except Exception as e:
            raise e
        return {
            "message": '更新成功'
        }
