#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict

from rest_framework.pagination import PageNumberPagination
from django.core.paginator import InvalidPage
from rest_framework.exceptions import NotFound
from rest_framework.response import Response

from common.utils.service_code import INFO_CODE


class CustomPageNumberPagination(PageNumberPagination):

    page_size_query_param = 'page_size'
    page_query_param = 'page'
    page_size = 10

    def paginate_queryset(self, queryset, request, view=None):
        """
        Paginate a queryset if required, either returning a
        page object, or `None` if pagination is not configured for this view.
        """
        page_size = self.get_page_size(request)
        if not page_size:
            return None
        paginator = self.django_paginator_class(queryset, page_size)
        page_number = request.query_params.get(self.page_query_param, 1)
        if page_number in self.last_page_strings:
            page_number = paginator.num_pages

        try:
            self.page = paginator.page(page_number)
        except InvalidPage as exc:
            msg = self.invalid_page_message.format(page_number=page_number,
                                                   message=str(exc))
            raise NotFound(msg)

        if paginator.num_pages > 1 and self.template is not None:
            # The browsable API should display pagination controls.
            self.display_page_controls = True

        self.request = request
        return list(self.page)

    def get_paginated_response(self, data):
        rst = {"bean": {}, "list": []}
        rst["list"] = data
        return Response(
            OrderedDict([('count', self.page.paginator.count),
                         ('page', self.page.number),
                         ('page_size', self.page.paginator.per_page),
                         ('code', INFO_CODE), ('msg', 'success'),
                         ('msg_show', '获取列表成功'), ('data', rst)]))

    def get_paginated_response_schema(self, schema):
        return {
            'type': 'object',
            'properties': {
                'count': {
                    'type': 'integer',
                    'example': 123,
                },
                'page': {
                    'type': 'integer',
                    'example': 1,
                },
                'num_pages': {
                    'type': 'integer',
                    'example': 5,
                },
                'page_size': {
                    'type': 'integer',
                    'example': 10,
                },
                'data': schema,
            },
        }
