# Path: db.py
# def create_db_connnection():
# def getConfig():
# 
# Path: lib/decorators.py
# def database_conn(func):
#     """Provides db cursor for decorated func."""
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         db = connect(host=db_config['host'],
#                              user=db_config['username'],
#                              passwd=db_config['password'],
#                              db=db_config['database'])
#         with closing(db.cursor()) as cursor:
#             result = func(cursor, *args, **kwargs)
#         return result
#     return wrapper
# 
# def memoize(func):
#     """Simple caching decorator.
# 
#     Puts result of the call to decorated function into
#     dictionary with key equals to positional args
#     supplied to function. Next call with the same
#     args will result in cache lookup instead of real
#     function call. Will not work with unhashable
#     positional args.
# 
#     Adopted from here:
#     https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
#     """
#     cache = {}
# 
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         try:
#             if args not in cache:
#                 cache[args] = func(*args, **kwargs)
#             return cache[args]
#         except TypeError:
#             return func(*args, **kwargs)
# 
#     return wrapper
# 
# Path: utils.py
# def build_tbpl_link(record):
#     # TODO: is branch valid?
#     tbpl_branch = record.branch.split('-Non-PGO')[0]
#     if tbpl_branch == 'Firefox':
#         treeherder_repo = 'mozilla-central'
#     else:
#         treeherder_repo = tbpl_branch.lower()
# 
#     vals = get_revision_range(treeherder_repo, record.keyrevision)
# 
#     link = ''
#     if vals:
#         params = []
# 
#         tbpl_platform = settings.TBPL_PLATFORMS[record.platform]
#         tbpl_test = settings.TBPL_TESTS[record.test]['jobname']
#         tbpl_tree = settings.TBPL_TREES[record.branch]
# 
#         if 'OSX' in tbpl_platform:
#             tbpl_tree = tbpl_tree.split(' pgo')[0]
# 
#         params.append(('repo', treeherder_repo))
#         params.append(('fromchange', vals[0]))
#         params.append(('tochange', vals[1]))
#         params.append(('filter-searchStr', '%s %s talos %s' % (tbpl_platform, tbpl_tree, tbpl_test)))
#         link = settings.TREEHERDER_URL
#         delim = '?'
#         for key, value in params:
#             link = "%s%s%s=%s" % (link, delim, key, value)
#             if delim == '?':
#                 delim = '&'
#         link = link.replace(' ', '%20')
# 
#     return link


import logging
import mailbox
import string
import time
import requests
import os
import re
import settings
from collections import namedtuple
from datetime import datetime, timedelta
from email.utils import parsedate
from itertools import chain
from urllib import urlencode
from urlparse import parse_qsl, urlsplit, urlunsplit
from db import app, getConfig
from lib.decorators import database_conn, memoize
from utils import build_tbpl_link

    now = app.config["now"]()

    query = """SELECT keyrevision, changesets FROM alerts
               WHERE DATE_SUB(%s, INTERVAL 14 DAY) < PUSH_DATE;"""
    db_cursor.execute(query, (now,))

    results = []
    for keyrev, csets in db_cursor.fetchall():
        results.append([keyrev, csets.split(',')])
    return results


@database_conn
def check_for_duplicate(db_cursor, record):
    # TODO: is this valid? we are checking if the branch is equal,
    # same with percent- in this case it already exists?!?s
    query = """SELECT id FROM alerts WHERE
               branch=%s AND test=%s AND platform=%s AND percent=%s"""
    db_cursor.execute(
        query,
        (record.branch, record.test, record.platform, record.percent))

    duplicate = None
    for row in db_cursor.fetchall():
        if row[0]:
            duplicate = row[0]
    return duplicate



# Path: db.py
# def create_db_connnection():
# def getConfig():
# 
# Path: lib/decorators.py
# def database_conn(func):
#     """Provides db cursor for decorated func."""
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         db = connect(host=db_config['host'],
#                              user=db_config['username'],
#                              passwd=db_config['password'],
#                              db=db_config['database'])
#         with closing(db.cursor()) as cursor:
#             result = func(cursor, *args, **kwargs)
#         return result
#     return wrapper
# 
# def memoize(func):
#     """Simple caching decorator.
# 
#     Puts result of the call to decorated function into
#     dictionary with key equals to positional args
#     supplied to function. Next call with the same
#     args will result in cache lookup instead of real
#     function call. Will not work with unhashable
#     positional args.
# 
#     Adopted from here:
#     https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
#     """
#     cache = {}
# 
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         try:
#             if args not in cache:
#                 cache[args] = func(*args, **kwargs)
#             return cache[args]
#         except TypeError:
#             return func(*args, **kwargs)
# 
#     return wrapper
# 
# Path: utils.py
# def build_tbpl_link(record):
#     # TODO: is branch valid?
#     tbpl_branch = record.branch.split('-Non-PGO')[0]
#     if tbpl_branch == 'Firefox':
#         treeherder_repo = 'mozilla-central'
#     else:
#         treeherder_repo = tbpl_branch.lower()
# 
#     vals = get_revision_range(treeherder_repo, record.keyrevision)
# 
#     link = ''
#     if vals:
#         params = []
# 
#         tbpl_platform = settings.TBPL_PLATFORMS[record.platform]
#         tbpl_test = settings.TBPL_TESTS[record.test]['jobname']
#         tbpl_tree = settings.TBPL_TREES[record.branch]
# 
#         if 'OSX' in tbpl_platform:
#             tbpl_tree = tbpl_tree.split(' pgo')[0]
# 
#         params.append(('repo', treeherder_repo))
#         params.append(('fromchange', vals[0]))
#         params.append(('tochange', vals[1]))
#         params.append(('filter-searchStr', '%s %s talos %s' % (tbpl_platform, tbpl_tree, tbpl_test)))
#         link = settings.TREEHERDER_URL
#         delim = '?'
#         for key, value in params:
#             link = "%s%s%s=%s" % (link, delim, key, value)
#             if delim == '?':
#                 delim = '&'
#         link = link.replace(' ', '%20')
# 
#     return link


# Path: parse_news.py
import logging
import mailbox
import string
import time
import requests
import os
import re
import settings
from collections import namedtuple
from datetime import datetime, timedelta
from email.utils import parsedate
from itertools import chain
from urllib import urlencode
from urlparse import parse_qsl, urlsplit, urlunsplit
from db import app, getConfig
from lib.decorators import database_conn, memoize
from utils import build_tbpl_link


    now = app.config["now"]()

    query = """SELECT keyrevision, changesets FROM alerts
               WHERE DATE_SUB(%s, INTERVAL 14 DAY) < PUSH_DATE;"""
    db_cursor.execute(query, (now,))

    results = []
    for keyrev, csets in db_cursor.fetchall():
        results.append([keyrev, csets.split(',')])
    return results


@database_conn
def check_for_duplicate(db_cursor, record):
    # TODO: is this valid? we are checking if the branch is equal,
    # same with percent- in this case it already exists?!?s
    query = """SELECT id FROM alerts WHERE
               branch=%s AND test=%s AND platform=%s AND percent=%s"""
    db_cursor.execute(
        query,
        (record.branch, record.test, record.platform, record.percent))

    duplicate = None
    for row in db_cursor.fetchall():
        if row[0]:
            duplicate = row[0]
    return duplicate



@database_conn