import datetime
import logging
import time

import praw
import requests


logger = logging.getLogger(__package__)


def _retrieve_comment_ids(submission_id):
    # https://www.reddit.com/r/redditdev/comments/5to97v/slug/ddoeedj/
    comments = requests.request(
        "GET",
        "http://apiv2.pushshift.io/reddit/get/comment_ids/{}"
        .format(submission_id)
    )
    return comments.json()["data"]


def _retrieve_submissions(query, subreddit, limit=100):
    # I love pushshift
    params = {
        "q": query,
        "subreddit": subreddit,
        "sort": "desc",
        "limit": limit
    }

    submissions = requests.request(
        "GET",
        "https://apiv2.pushshift.io/reddit/submission/search/",
        params=params
    )
    return submissions.json()["data"]


def _create_reddit_instance():
    return praw.Reddit("reddit")


def get_comment_stream():
    reddit = _create_reddit_instance()

    return reddit.subreddit("anime").stream.comments()


def get_comments_from_submission(submission_id):
    reddit = _create_reddit_instance()

    comments = _retrieve_comment_ids(submission_id)

    return reddit.info(comments)


def get_comments_from_ftfs():
    reddit = _create_reddit_instance()

    # FIXME: This is so misplaced
    # TODO: MAKE THIS LESS SHIT
    d = datetime.date.today()
    e = datetime.date(d.year, 1, 1)

    threshold = time.mktime(e.timetuple())

    ftfs = _retrieve_submissions("Free Talk Fridays",
                                 subreddit="anime", limit=60)

    # TODO: Generator?
    comments = []

    for ftf in ftfs:
        # Don't use FTFs that were made before the start of the year
        if ftf["created_utc"] < threshold:
            logger.debug("Skipping FTF: {} ({}) because creation date is "
                         "below threshold".format(ftf["title"], ftf["id"]))
            continue

        # Don't make Pushshift servers angry
        time.sleep(5)

        logger.info("Retrieving comment ids for FTF: {} ({})"
                    .format(ftf["title"], ftf["id"]))

        comments.extend(_retrieve_comment_ids(ftf["id"]))

    logger.debug("Received {} comments".format(len(comments)))

    # Sorry, reddit servers
    return reddit.info(comments)

@@ -436,181 +436,447 @@
 ons(
-query, subreddit, limit=100):%0A    # I love pushshif
+**params):%0A    %22%22%22%0A    https://goo.gl/mHn7P3%0A%0A    :param q: The search keyword(s) or phrase%0A    :param subreddit: Restrict to a specific subreddi
 t%0A    
+:
 param
-s = %7B%0A        %22q%22: query,%0A        %22subreddit%22: subreddit,%0A        %22sort%22: %22desc%22,%0A        %22limit%22: limit%0A    %7D%0A
+ limit: Return up to limit comments%0A    :param sort: Sort by comment ids in descending or ascending order%0A    :param after: Show only comments older than epoch date. The API also%0A        understands m,h,d (i.e. 4h to search the previous 4 hours, etc.)%0A    %22%22%22%0A    # I love pushshift
 %0A   
@@ -1666,16 +1666,82 @@
 tuple())
+%0A    # Force to int because reasons%0A    threshold = int(threshold)
 %0A%0A    ft
@@ -1767,16 +1767,18 @@
 issions(
+q=
 %22Free Ta
@@ -1793,236 +1793,90 @@
 ys%22,
-%0A                                 subreddit=%22anime%22, limit=60)%0A%0A    # TODO: Generator?%0A    comments = %5B%5D%0A%0A    for ftf in ftfs:%0A        # Don't use FTFs that were made before the start of the year%0A        if ftf%5B%22created_utc%22%5D %3C 
+ subreddit=%22anime%22,%0A                                 limit=60, sort=%22desc%22, after=
 thre
@@ -1884,182 +1884,73 @@
 hold
-:
+)%0A
 %0A    
-        logger.debug(%22Skipping FTF: %7B%7D (%7B%7D) because creation date is %22%0A                         %22below threshold%22.format(ftf%5B%22title%22%5D, ftf%5B%22id%22%5D))%0A            continue%0A
+# TODO: Generator?%0A    comments = %5B%5D%0A%0A    for ftf in ftfs:
 %0A   

Use PushShift's `after` to filter out old FTFs, instead of doing it manually