#!/usr/bin/python2
# coding=utf-8

import praw
import sqlite3
import subprocess

import config
import feed

# set to true when testing without tweeting/commiting
LOGGER = config.LOGGER
TESTING = config.TESTING

LONG_TEXT_MIN_SCORE = 1000
HIGH_SCORE = 500
TWITTER_LIMIT = 140

# database initialization
# sqlite> create table submissions(id text, url text);
DB = sqlite3.connect("./jokes_db")
CURSOR = DB.cursor()

def log(msg):
	if LOGGER:
		print msg

def id_in_db(post_id):
	CURSOR.execute("select id from submissions where id=?", [post_id])
	result =  CURSOR.fetchone()

	if result:
		return True
	else:
		return False


def save_in_db(post_id, post_url):
	sql = "insert into submissions values(?, ?)"
	log("SQL: " + sql + "\n" + post_id + ", " + post_url + "\n")
	CURSOR.execute(sql, [post_id, post_url])


def get_url(post_id):
	return "redd.it/" + post_id


def format_twitter_all(post_id, title, text):
	return "%s\n\n%s\n\n%s" %(title, text, get_url(post_id))


def format_twitter_title(post_id, title):
	return "%s\n\n%s" %(title, get_url(post_id))


def format_twitter_url(post_id):
	return "%s" % get_url(post_id)


def tweet(tweet_text):
	text = tweet_text.encode('utf-8')
	print "TWEETING: " + text

	if not TESTING:
		try:
			return subprocess.call([config.twitter_path, "set", text])
		except Exception as e:
			print str(e)
			return 0
	else:
		return 0


def main():
	# https://praw.readthedocs.org/en/v3.0.0/pages/writing_a_bot.html#writing-a-bot
	r = praw.Reddit('PRAW related-question monitor by /u/_Daimon_ v 1.0. '
		'Url: https://praw.readthedocs.org/en/latest/'
		'pages/writing_a_bot.html')

	subreddit = r.get_subreddit('jokes')

	feed.init()

	for submission in subreddit.get_hot(limit=20):
		title = submission.title
		post_id = submission.id
		score = submission.score
		text = submission.selftext


		log("%s : %d : %s" %(title, score, get_url(post_id)))
		if score < HIGH_SCORE:
			log("*** LOW SCORE")

			continue

		if id_in_db(post_id):
			log("*** ALREADY IN DATABASE")
			continue

		twitter_text = format_twitter_all(post_id, title, submission.selftext)

		if len(twitter_text) < TWITTER_LIMIT:
			status = tweet(twitter_text)

			if status:
				save_in_db(post_id, get_url(post_id))

		else:
			if score >= LONG_TEXT_MIN_SCORE and not feed.item_in_feed("https://" + get_url(post_id)):
				feed.add_entry(title, "https://" + get_url(post_id), text)
				print "NEW RSS FEED ===============\n" + title + " - " + get_url(post_id)

	if not TESTING:
		DB.commit()

	feed.close()

if __name__ == "__main__":
	main()

@@ -72,16 +72,32 @@
 bprocess
+%0Aimport facebook
 %0A%0Aimport
@@ -115,16 +115,31 @@
 ort feed
+%0Aimport secrets
 %0A%0A# set 
@@ -831,24 +831,101 @@
 ost_url%5D)%0A%0A%0A
+def get_long_url(post_id):%0A%09return %22https://reddit.com/r/jokes/%22 + post_id%0A%0A%0A
 def get_url(
@@ -1472,16 +1472,224 @@
 turn 0%0A%0A
+def publish_facebook(title, text, url):%0A%09token = secrets.FB_TOKEN%0A%09api = facebook.GraphAPI(token)%0A%09msg = title.encode(%22utf-8%22) + %22%5Cn%5Cn%22 + text.encode(%22utf-8%22) + %22%5Cn%5Cn%22 + url%0A%09api.put_wall_post(msg)%0A%09%0A%09return%0A
 %0Adef mai
@@ -2668,32 +2668,37 @@
 https://%22 + get_
+long_
 url(post_id), te
@@ -2701,16 +2701,73 @@
 , text)%0A
+%09%09%09%09publish_facebook(title, text, get_long_url(post_id))%0A
 %09%09%09%09prin

add facebook bot :)