# The MIT License (MIT)
#
# Copyright (c) 2016 Yutkin Dmitry
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from __future__ import print_function

import requests
import sys
import datetime
from datetime import timedelta
from multiprocessing import current_process, cpu_count

from .argparser import parse_args
from .constants import VKAPI_URL, VKAPI_VERSION, APP_ACCESS_KEY
from .utils import get_page_id, VKApiError, pretty_print
from .post import Post


import logging

logging.basicConfig(
    level=logging.INFO,
    format="[\033[92m%(levelname)s %(asctime)s\033[0m]: %(message)s",
    datefmt="%m/%d/%Y %I:%M:%S %p",
)
# Removing noisy debug messages from lib request
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
logger = logging.getLogger()


class PostDownloader:
    def __init__(self, page_id, from_date=None, to_date=None):
        self.page_id = page_id
        self.api_url = VKAPI_URL + "wall.get"
        self.request_params = {
            "owner_id": self.page_id,
            "v": VKAPI_VERSION,
            "access_token": APP_ACCESS_KEY,
        }
        self.from_date = from_date or datetime.date.min
        self.to_date = to_date or datetime.date.max

    def _number_of_posts(self):
        """ Returns total number of post on the page """

        self.request_params.update({"offset": 0, "count": 1})

        response = requests.get(self.api_url, params=self.request_params).json()

        if "error" in response:
            raise VKApiError(response["error"]["error_msg"])

        total_posts = response["response"]["count"]
        logger.debug("Posts to fetch: {}".format(total_posts))
        return total_posts

    def fetch(self, init_offset=0, num_to_fetch=None):
        """ Downloads 'num_to_fetch' posts starting from 'init_offset' position """
        num_to_fetch = num_to_fetch or self._number_of_posts()

        self.request_params['offset'] = init_offset
        self.request_params['count'] = min(num_to_fetch, 100)

        logger.debug(
            "{} trying to download {} posts".format(
                current_process().name, num_to_fetch
            )
        )

        fetched_posts, fetched_counter = [], 0
        while fetched_counter != num_to_fetch:
            response = requests.get(self.api_url, self.request_params).json()

            if "error" in response:
                raise VKApiError(response["error"]["error_msg"])

            posts = response["response"]["items"]
            fetched_counter += len(posts)

            logger.debug(
                "{} downloaded {}/{} posts".format(
                    current_process().name, fetched_counter, num_to_fetch
                )
            )

            for post in posts:
                post = Post(
                    id=post["id"],