import logging
import os
import praw
import re
import random
import time
import traceback
import urlparse
import urllib2
import urllib
import sys

USER_AGENT = "Archives to archive.is (/u/justcool393) v1.1"
REDDIT_DOMAIN = "api.reddit.com"
INFO = "/r/SnapshillBot"
CONTACT = "/message/compose?to=\/r\/SnapshillBot"
ARCHIVE_SELF = os.environ.get('ARCHIVE_SELF') is "1"
SUBMISSION_SCAN_COUNT = 10
WAIT_TIME = 4 * 60

archived = []
user = os.environ['REDDIT_USER']


def main():
    r = praw.Reddit(USER_AGENT, domain=REDDIT_DOMAIN)
    r.login(user, os.environ.get("REDDIT_PASS"))
    logging.info("Logged in and started post archiving.")
    add_archived(r)

    check_at = 3600
    last_checked = 0
    times_zero = 1

    arch = archive_submissions(r, 50, 0)
    # Check the last 50 posts on startup
    while True:
        if time.time() - last_checked > check_at:
            last_checked = time.time()
            if arch == 0:
                times_zero += 1
            else:
                logging.info("Last " + str((check_at * times_zero) / 60)
                             + "min: " + str(arch))

                arch = 0
                times_zero = 1

        arch += archive_submissions(r, SUBMISSION_SCAN_COUNT, WAIT_TIME)


def add_archived(r):
    for c in r.user.get_comments(sort='new', limit=None):
        pid = c.parent_id
        if pid is None or pid in archived:
            continue
        archived.append(pid)


def archive_submissions(r, count, delay):
    archived_posts = 0

    for submission in r.get_new(limit=count):
        if submission.id in archived:
            continue

        submission.replace_more_comments(limit=None, threshold=0)

        commented = check_commented(submission)

        if commented:
            archived.append(submission.id)
            continue

        try:
            if archive_and_post(submission):
                archived_posts += 1
                archived.append(submission.id)
        except UnicodeEncodeError:
            logging.error("Error (UEE): Submission ID: " + submission.id + ")")

    time.sleep(delay)
    return archived_posts


def check_commented(s):
    flat_comments = praw.helpers.flatten_tree(s.comments)
    for c in flat_comments:
        if c.author is None:
            continue
        if c.author.name == user:
            return True
    return False


def get_response(url, data):
    res = urllib2.urlopen(fix_url(url), data)
    return res.read()


def get_redirected_url(data):
    return re.findall('http[s]://archive.(today|is|li)/[0-z]{1,8}', data)[0]


def archive_and_post(s):
    if s.is_self and not ARCHIVE_SELF:
        return False
    arch_post = archive(s.url)
    return post(s, arch_post)


def archive(url):
    pairs = {"url": url}
    return get_redirected_url(get_response("https://archive.is/submit/",
                                           urllib.urlencode(pairs)))


def post(s, archive_link):
    comment = """
Automatically archived [here]({link}).

*I am a bot. ([Info]({info}) | [Contact]({contact}))*
"""

    try:
        s.add_comment(
            comment.format(link=archive_link, info=INFO, contact=CONTACT))
    except Exception as ex:
        logging.error(
            "Error adding comment. (Submission ID: " + str(s.id) + ")")
        logging.error(str(ex))
        return False
    return True


def urlEncodeNonAscii(b):
    return re.sub('[\x80-\xFF]', lambda c: '%%%02x' % ord(c.group(0)), b)


def fix_url(iri):
    parts = urlparse.urlparse(iri)
    return urlparse.urlunparse(
        part.encode('idna') if parti == 1 else urlEncodeNonAscii(
            part.encode('utf-8'))
        for parti, part in enumerate(parts)
    )


def setup_logging():
    root = logging.getLogger()
    root.setLevel(logging.INFO)
    logging.getLogger("requests").setLevel(logging.WARNING)
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.INFO)

    root.addHandler(ch)


def log_crash(e):
    logging.error("Error occurred in the bot restarting in 15 seconds...")
    logging.error("Details: " + str(e))
    traceback.print_exc()
    time.sleep(15)
    sys.exit(1)  # Signal to the host that we crashed


try:
    setup_logging()
    main()
except (NameError, SyntaxError, AttributeError) as e:
    logging.error(str(e))
    time.sleep(86400)  # Sleep for 1 day so we don't restart.
except Exception as e:
    log_crash(e)
@@ -2364,121 +2364,20 @@
 get_
-response(url, data):%0A    res = urllib2.urlopen(fix_url(url), data)%0A    return res.read()%0A%0A%0Adef get_redirected_url
+archive_link
 (dat
@@ -2402,17 +2402,17 @@
 findall(
-'
+%22
 http%5Bs%5D:
@@ -2420,16 +2420,17 @@
 /archive
+%5C
 .(today%7C
@@ -2446,17 +2446,17 @@
 -z%5D%7B1,8%7D
-'
+%22
 , data)%5B
@@ -2661,141 +2661,120 @@
   re
-turn get_redirected_url(get_response(%22https://archive.is/submit/%22,%0A                                           urllib.urlencode(pairs)
+s = urllib2.urlopen(%22https://archive.is/submit/%22, urllib.urlencode(pairs))%0A    return get_archive_link(res.read(
 ))%0A%0A
@@ -2861,11 +2861,20 @@
 k%7D).
+ %7Bquip%7D
 %0A%0A*
+%5E(
 I am
@@ -2884,15 +2884,20 @@
 bot.
- 
+) %5E%5C
 (%5B
+*
 Info
+*
 %5D(%7Bi
@@ -2906,18 +2906,22 @@
 o%7D) 
-%7C %5B
+%5E/ %5E%5B*
 Contact
+*
 %5D(%7Bc
@@ -3040,16 +3040,52 @@
 =CONTACT
+,%0A                           quip=%22%22
 ))%0A    e
@@ -3129,29 +3129,16 @@
 g.error(
-%0A            
 %22Error a
@@ -3150,17 +3150,16 @@
  comment
-.
  (Submis
@@ -3261,345 +3261,59 @@
 ue%0A%0A
-%0A
 def 
-urlEncodeNonAscii(b):%0A    return re.sub('%5B%5Cx80-%5CxFF%5D', lambda c: '%25%25%2502x' %25 ord(c.group(0)), b)%0A%0A%0Adef fix_url(iri):%0A    parts = urlparse.urlparse(iri)%0A    return urlparse.urlunparse(%0A        part.encode('idna') if parti == 1 else urlEncodeNonAscii(%0A            part.encode('utf-8'))%0A        for parti, part in enumerate(parts)%0A    )
+get_quip(subreddit):%0A    pass # TODO: Implement
 %0A%0A%0Ad

Fix a problem