#!/usr/bin/env python
# coding=utf-8
"""
Copyright (c) 2016, Ahmed Şeref
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of mongo_pager nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import math

__author__ = u'Ahmed Şeref GÜNEYSU'


class MongoPager(object):
    """
    Usage:
    >>> from pymongo import MongoClient
    >>> import uuid
    >>> from pymongopager import MongoPager
    >>> db = MongoClient("mongodb://localhost/test")["test"]
    >>> contents_cursor = cursor=db.get_collection("contents").find({})

    >>> _ = db.get_collection("contents").remove({})
    >>> for i in range(10):
    ...    _ = db.get_collection("contents").insert_one({'_id': uuid.uuid1().__str__()})

    >>> print contents_cursor.clone().count()
    10
    >>> pages = MongoPager(cursor=contents_cursor.clone(),
    ...                   limitpages=None,
    ...                   perpage=3)
    >>> for page in pages:
    ...     print page.count(with_limit_and_skip=True)
    3
    3
    3
    1
    >>> _ = db.get_collection("contents").remove({})
    >>> for i in range(100):
    ...    _ = db.get_collection("contents").insert_one({'_id': uuid.uuid1().__str__()})

    >>> print contents_cursor.clone().count()
    100
    >>> pages = MongoPager(cursor=contents_cursor.clone(),
    ...                   limitpages=4,
    ...                   perpage=35)
    >>> for page in pages:
    ...     print page.count(with_limit_and_skip=True)
    35
    35
    30
    """

    def __init__(self, cursor, page=0, perpage=25, limitpages=None):
        """
        :param cursor: Cursor object that would be paged.
        :type cursor: pymongo.cursor.CursorType

        :param limitpages: If set to `0` or `None` iterates all pages until cursor contains no documents.
        :type limitpages: int

        :param perpage:
        :type perpage: int

        :param page:
        :type page: int
        """
        self.page = page
        self.cursor = cursor
        self.perpage = perpage

        self.limitpages = limitpages or int(math.ceil(float(cursor.count()) / self.perpage))

    def __iter__(self):
        return self

    def next(self):
        if (self.limitpages != 0 or self.limitpages) and self.page == self.limitpages:
            raise StopIteration()
        self.page += 1
        cursor = self.cursor.clone().skip((self.page - 1) * self.perpage).limit(self.perpage)
        if cursor.count(with_limit_and_skip=True) == 0:
            raise StopIteration()
        else:
            return cursor
