import praw
import webbrowser
import json
import time
import requests
import re
import sys

def main():

	useragent = "babelbot by /u/alexbalez"
	clientid = XXXXX
	client_secret = XXXXX
	filename = 'oauth.txt'


	r = praw.Reddit(useragent)
	r.set_oauth_app_info(clientid, client_secret, redirect_uri='http://127.0.0.1:65010/authorize_callback')
	#first_oauth(r)
	#access_info = oauth(r)

	saved_scope_token = read_saved_token(filename)
	access_info = r.refresh_access_information(saved_scope_token['refresh_token'])
	save_refresh_token(access_info, filename)

	user= r.get_me()
	print 'Logged in as', user.name + ',', user.comment_karma , 'karma'

	while True:
		check_for_mentions(r)
		print 'Sleeping...'
		time.sleep(60)

def check_for_mentions(r):

	print 'Checking for new mentions...'
	messages = r.get_unread(unset_has_mail=True, update_user=True)

	for message in messages:
		try:
			comment = r.get_info(thing_id=message.parent_id)
			print 'Mention found:', comment.body
			data = {'find': comment.body}
			req = requests.post("https://libraryofbabel.info/search.cgi", data=data)
		
			#f = open("ht.html", 'w')
			#f.write(req.text)

			match = re.search('<h3>with random English words: .{1,}Title: <b>([a-zA-Z, ]{1,}).{1,} Page: <b>(\d{1,}).{1,} "postform\(\'([a-zA-z\d]{1,}).{1,}(-w\d-s\d-v\d\d)', req.text)
			title = match.group(1)
			m2 = re.search('w(\d)-s(\d)-v(\d\d)', match.group(4))
			location = '**Location:** Wall '+m2.group(1)+', Shelf '+m2.group(2)+', Volume '+m2.group(3)
			page = '[**Page:** ' + match.group(2) + '](https://libraryofbabel.info/book.cgi?'+match.group(3)+match.group(4)+':'+match.group(2)+')'

			#print location

			message.reply('Found in the [Library of Babel](https://libraryofbabel.info):\n\n'+location+'  \n'+'**Title:** '+title+'  \n'+page)

			message.mark_as_read()
		except:
			print 'Error.', sys.exc_info()[0]






def first_oauth(r):
	# this only ever needs to run once to get the required access using oauth
	# HOW TO: run this once, allow access to user on website, copy key at the end of the url
	# run oauth(r) once to get proper token, write it to the file for safe keeping

	scopes = 'edit flair history identity mysubreddits privatemessages read submit'
	url = r.get_authorize_url('uniquekey', scopes, True)
	webbrowser.open(url)

	exit()

def oauth(r):

	key = XXXXX
	access_info = r.get_access_information(key)
	r.set_access_credentials(**access_info)
	user = r.get_me()
	print user.name, user.comment_karma

	return access_info

def save_refresh_token(refresh, filename):
	
	# scope isn't serializable nor needed, so we can delete it
	del refresh['scope']

	try:
		f = open(filename, 'w')
		json.dump(refresh, f)
	except:
		print 'Couldn\'t write to', filename
		exit()
	else:
		print 'Refreshed token saved to', filename

	f.close()

def read_saved_token(filename):

	try:
		f = open(filename, 'r')
		access_information = json.loads(f.read())
	except:
		print 'Couldn\'t open', filename, '!'
		exit()
	else:
		print 'Refresh token loaded from', filename

	f.close()
	return access_information

main()
