#! /usr/bin/env python3
import json
import tweepy
from tweepy.parsers import JSONParser
import Keys
from pymongo import MongoClient

def _twit_auth():
    consumer_key = Keys.consumer_key
    consumer_secret = Keys.consumer_secret
    access_key = Keys.access_key
    access_secret = Keys.access_secret
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth, parser=JSONParser())

    return api

def _send_url(status_id, user):
    auth = _twit_auth()
    post = auth.get_status(status_id)['text']

    dbclient = MongoClient('localhost', 27017)
    db = dbclient.TIL_Posts

    all_posts = db.posts.distinct("post")

    for cnt in all_posts:
        if post in cnt:
            _doc = db.posts.find_one({"post": cnt})
            text = '@%s %s' % (user, _doc["url"])
            _twit_auth().update_status(text, status_id)

def main():

    auth = _twit_auth()

    twt = auth.search('to:TIL_Bot_')

    dbclient = MongoClient('localhost', 27017)
    db = dbclient.TIL_Posts

    for tweet in twt['statuses']:
        if db.reply.find({"id": tweet['in_reply_to_status_id']}).count() == 0 and tweet['user']['screen_name'] != 'TIL_Bot_':
            _send_url(tweet['in_reply_to_status_id'], tweet['user']['screen_name'])
            tweet_data = {'id':tweet['in_reply_to_status_id'], 'user':tweet['user']['screen_name'], 'text':tweet['text']}
            db.reply.insert_one(tweet_data).inserted_id

if __name__ == '__main__':
    main()

